Python基础-9.3 继承

本文详细介绍了Python中的继承概念,包括子类如何继承父类的属性和方法,如何通过`__init__()`初始化子类,Python 2.7中的`super()`函数使用,以及如何重写和自定义子类的方法。还提到了将实例作为属性来创建更复杂的类结构,例如Battery类的创建及其方法。最后,鼓励读者通过实践练习进一步巩固这些概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

·一个类继承另一个类时,自动获取另一个类的所有属性和方法;原有的类为父类,新类称为子类。子类继承父类的所有属性和方法,同时还可定义自己的属性和方法。

 

9.3.1 子类的方法 __inint__()

创建electric_car继承前面的Car类

class ElectricCar(Car):  # 定义子类,需在括号里指定父类名称
    """电动汽车的独特之处"""

    def __init__(self,make, model, year):
        """初始化父类属性"""
        super().__init__(make, model, year)  # 调用父类的方法__init__,让ElectricCar包含父类的所有属性


my_electric_car = ElectricCar('bmw', 'mosel s', 2016)
my_electric_car.get_descriptive_name()

 

9.3.2 Python2.7中的继承

1.函数super()需要两个实参:子类名和对象self。

2.在定义父类时在括号内指定object。

class Car(object):
    def __init__(self,make, model, year):
        --snip--
        
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)
        --snip--

 

9.3.3 给子类定义属性和方法

class ElectricCar(Car):  # 定义子类,需在括号里指定父类名称
    """电动汽车的独特之处"""

    def __init__(self,make, model, year):
        """
        初始化父类属性
        再初始化电动汽车特有的属性
        """
        super().__init__(make, model, year)  # 调用父类的方法__init__,让ElectricCar包含弗雷的所有属性
        self.battery_size = 70

    def describe_battery(self):
        """打印一条描述电瓶容量的消息"""
        print("This car has a " + str(self.battery_size) + "-kwh battery")


my_electric_car = ElectricCar('bmw', 'mosel s', 2016)
my_electric_car.get_descriptive_name()
my_electric_car.describe_battery()

9.3.4 重写父类的方法

在子类中定义一个与需要重写的父类重名的方法,这样Python会忽略父类中的该方法,使用子类中的。

9.3.5 将实例用作属性

增加Battery()类,并添加相关方法

class Car():
    """一次模拟汽车的简单尝试"""

    def __init__(self, make, model, year):  # 注意__inint__下划线是左右两边各两个,若出错会报出takes no arguments的错误
        """初始化描述汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        # 添加odometer_reading属性,使其初始值为0
        self.odometer_reading = 20

    def get_descriptive_name(self):
        """返回整洁的描述信息"""
        long_name = str(self.year) + " " + self.make + ' ' + self.model
        print(long_name.title())

    def update_odometer(self, mileage):
        """将里程表读数设置为指定的值"""
        # self.odometer_reading = mileage
        """                                                                                          
        将里程表读数设置为指定的值                                                                                
        禁止将里程表读数往回调                                                                                  
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer !")

    def increment_odometer(self, miles):
        """
        将里程表读数增加指定的量
        禁止增加量为负数
        """
        if miles >= 0:
            self.odometer_reading += miles
        else:
            print("You can't add negative number on  odometer !")

    def read_odometer(self):
        """打印一条指出汽车里程的消息"""
        print("This car has " + str(self.odometer_reading) + " miles on it.")


class Battery():
    """一次模拟电动汽车电瓶的简单尝试"""
    def __init__(self, battery_size=70):
        """"初始化电瓶属性"""
        self.battery_size = battery_size

    def describe_battery(self):
        """打印一条描述电瓶容量的消息"""
        print("This car has a " + str(self.battery_size) + "-kwh battery")

    def get_range(self):
        """打印一条消息,指出电瓶车的续航里程"""
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270
        message = "This car can go approximately " + str(range)
        message += " miles on a full charge"
        print(message)


class ElectricCar(Car):  # 定义子类,需在括号里指定父类名称
    """电动汽车的独特之处"""

    def __init__(self, make, model, year):
        """
        初始化父类属性
        再初始化电动汽车特有的属性
        """
        super().__init__(make, model, year)  # 调用父类的方法__init__,让ElectricCar包含弗雷的所有属性
        self.battery = Battery()


my_electric_car = ElectricCar('bmw', 'model s', 2016)
my_electric_car.get_descriptive_name()
my_electric_car.battery.describe_battery()
my_electric_car.battery.get_range()

 

练习:

9-6

# 9-6 冰淇淋小店
class Restaurant():
    def __init__(self, restaurant_name, cuisine_type):
        self.name = restaurant_name
        self.type = cuisine_type

    def describe_restaurant(self):
        print("\nThe restaurant's name is " + self.name.title() + "!")
        print("\nThe restaurant is " + self.type + "!")

    def open_restsurant(self):
        print("\n" + self.name.title() + " is open !")


class IceCreamStand(Restaurant):
    def __init__(self, restaurant_name='gg', cuisine_type='dd'):
        # flavors = []
        super().__init__(restaurant_name, cuisine_type)
        self.flavors = ['蓝莓', '草莓', '芒果']
        print(self.flavors)


restaurant1 = IceCreamStand()

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值