Python 面向对象继承

1.子类继承

main.py

import car
if __name__ == '__main__':


    my_car = car.Car('audi','a4',2016)
    print(my_car.get_descriptive_name())
    my_car.update_year(8888)
    print(my_car.get_descriptive_name())

    my_tesla = car.ElectricCar('tesla','model s',2017)
    print(my_tesla.get_descriptive_name())
    my_tesla.update_year(2020)
    print(my_tesla.get_descriptive_name())

car.py

#父类
class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name

    def update_year(self,year):
        self.year = year
        
#子类
class ElectricCar(Car):
    def __init__(self,make,model,year):
        super().__init__(make,model,year)


1、父类必须包含在当前文件中,且位于子类前面。
2、定义子类时,必须在括号内指明父类的名称。子类中方法 def __init__() 接受创建Car实例所需的信息。
3、 super() 是一个特殊函数,调用父类方法的__init__(),让ElectricCar实例包含父类的所有属性。

2. 给子类定义属性和方法

car.py

class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name

    def update_year(self,year):
        self.year = year
class ElectricCar(Car):
    def __init__(self,make,model,year):
        super().__init__(make,model,year)
        # 定义电动汽车属性----电池
        self.battery = 70
    def describe_battery(self):
        print("This Car has a "+str(self.battery)+" kWh battery")







Python 面向对象继承_第1张图片

3. 将实例用作属性

main.py

import car
if __name__ == '__main__':


    my_tesla = car.ElectricCar('tesla','model s',2017)
    print(my_tesla.get_descriptive_name())
    my_tesla.update_year(2020)


    print(my_tesla.get_descriptive_name())
    
    """下面这句是属性"""
    my_tesla.battery.describe_battery()

Car.py

class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self):
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name

    def update_year(self,year):
        self.year = year


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

    def describe_battery(self):
        print("This car has "+str(self.battery_size)+" -kWh battery")


class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init__(make, model, year)
        # 定义电动汽车属性----电池
        self.battery = Battery()



Python 面向对象继承_第2张图片

你可能感兴趣的:(Python,python,类,面向对象编程)