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()

  

 运行结果:

Audi A4 2016 0
车辆行驶里程: 1000
Tesla Model S 2017 0
最大行驶里程: 350

 

posted @ 2017-07-23 17:55  星瑞  阅读(261)  评论(0编辑  收藏  举报