python之类的继承

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之类的继承相关的知识,希望对你有一定的参考价值。

 

# 类的的操作实例
# 子类ECar继承父类Car,并将实例Battery用作属性
class Car():
    def __init__(self, name, model, year):
        self.name = name
        self.model = model
        self.year = year
        self.odometer = 0  # 里程数,默认值为0

    def des_info(self):
        print(self.name.title(), self.model, self.year, self.odometer)

    def set_odometer(self, num):
        self.odometer = num

    def get_odometer(self):
        print(‘车辆行驶里程:‘, self.odometer)


class ECar(Car):
    ‘‘‘子类ECar继承父类Car,具有特殊属性battery‘‘‘

    def __init__(self, name, model, year):
        ‘‘‘初始化父类属性,再初始化特有属性‘‘‘
        super().__init__(name, model, year)
        self.battery = Battery()  # 将实例用作属性

    def get_meter(self):
        print(‘最大行驶里程:‘, self.battery.get_meter())


class Battery():
    def __init__(self, size=70):
        self.size = size

    def get_meter(self):
        ‘‘‘电池可行驶的最大里程‘‘‘
        miles = self.size * 5
        return miles

 

# 测试代码

my_car = Car(‘Audi‘, ‘A4‘, 2016)
my_car.des_info()
my_car.set_odometer(1000)
my_car.get_odometer()

your_car = ECar(‘tesla‘, ‘Model S‘, 2017)
your_car.des_info()
your_car.get_meter()

  

 



以上是关于python之类的继承的主要内容,如果未能解决你的问题,请参考以下文章

Python之类的继承

python之类的继承

python之类的相关名词-继承-

python之类之多继承

Python学习之类的继承

16python面对对象之类和继承