继承

什么是继承?

  • 编写类时,并非总要从空白开始。如果要编写的类是另一个现成类的特殊版本,可使用继承。
  • 一个类继承另一个类时,将自动获得另一个类的所有属性和方法。现有的类称为父类,而新类称为子类。
  • 子类继承了其父类的所有属性和方法,同时也可以定义自己的属性和方法。

 

1、子类的方法__init__

创建子类时,首先要完成的是将父类的所有属性和方法继承,这里使用子类的方法 __init__();




#继承
#子类的方法__init__()

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

    def read_odometer(self):
        print("This car has" + str(self.odometer_reading) + "mile on it.")

    def update_odomter(self,mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage

        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self,miles):
        self.odometer_reading += miles

class ElectricCar(Car):
    """电动汽车的独特"""

    def __init__(self,make,model,year):
        """初始化父类的属性"""
        super().__init__(make,model,year)

my_tesla = ElectricCar('tesla','model X',2018)
print(my_tesla.get_descriptive_name())




执行结果:



1 2018 Tesla Model X



注意点:

  1. 创建子类时,父类必须包含在当前文件中,且位于子类前面。
  2. super()是一个特殊函数,帮助父类和子类关联起来。
  3. 父类也称为超类(superclass)

 

1.1、给子类定义属性和方法

在一个类继承另一类后,可添加区分子类和父类所需的新属性和方法。




python子类super python 子类_python子类super

python子类super python 子类_父类_02

1 class Car():
 2     """一次模拟汽车的简单尝试"""
 3     def __init__(self,make,model,year):
 4         self.make = make
 5         self.model = model
 6         self.year = year
 7         self.odometer_reading = 0
 8 
 9     def get_descriptive_name(self):
10         long_name = str(self.year) + " " + self.make + " " + self.model
11         return long_name.title()
12 
13     def read_odometer(self):
14         print("This car has" + str(self.odometer_reading) + "mile on it.")
15 
16     def update_odomter(self,mileage):
17         if mileage >= self.odometer_reading:
18             self.odometer_reading = mileage
19 
20         else:
21             print("You can't roll back an odometer!")
22 
23     def increment_odometer(self,miles):
24         self.odometer_reading += miles
25 
26 class ElectricCar(Car):
27     """电动汽车的独特"""
28 
29     def __init__(self,make,model,year):
30         """初始化父类的属性"""
31         super().__init__(make,model,year)
32 
33         # 给子类定义属性和方法
34         self.battery_size = 70
35 
36     #给子类定义属性和方法
37     def describe_battery(self):
38         """打印一条描述电瓶容量的消息"""
39         print("This car has a " + str(self.battery_size) + "-KWh battery.")
40 
41 my_tesla = ElectricCar('tesla','model X',2018)
42 print(my_tesla.get_descriptive_name())
43 my_tesla.describe_battery()


View Code


执行结果:



1 2018 Tesla Model X
2 This car has a 70-KWh battery.



 

1.2、重写父类的方法

  1. 如果父类中存在的一个方法完全不适用于子类,那么可以直接在子类中对父类的方法进行重写。
  2. 要求子类中重写的方法要与父类的同名,这样代码就不会执行父类方法,而只关注子类的方法
1 class Car():
 2     --snip--
 3 
 4      def fill_gas_tank():
 5         """油箱"""
 6         print("This car need a gas tank.")
 7 
 8 class ElectricCar(Car):
 9     --snip--
10     #重写父类的方法
11     def fill_gas_tank():
12         """电动汽车没有油箱"""
13         print("This car doesn't need a gas tank.")



 

1.3、将实例用作属性

  1. 定义一个新类,并且没有任何继承
  2. 在子类中,添加一个属性,指向新建的父类;这里是self.battery = Battery()

 



1 class Car():
 2     """一次模拟汽车的简单尝试"""
 3     def __init__(self,make,model,year):
 4         self.make = make
 5         self.model = model
 6         self.year = year
 7         self.odometer_reading = 0
 8 
 9     def get_descriptive_name(self):
10         long_name = str(self.year) + " " + self.make + " " + self.model
11         return long_name.title()
12 
13     def read_odometer(self):
14         print("This car has" + str(self.odometer_reading) + "mile on it.")
15 
16     def update_odomter(self,mileage):
17         if mileage >= self.odometer_reading:
18             self.odometer_reading = mileage
19 
20         else:
21             print("You can't roll back an odometer!")
22 
23     def increment_odometer(self,miles):
24         self.odometer_reading += miles
25 
26 
27 # 将实例用作属性
28 class Battery():
29     def __init__(self, battery_size=70):
30         """初始化电瓶的属性"""
31         self.battery_size = battery_size
32 
33     def describe_battery(self):
34         """打印一条描述电瓶容量的信息"""
35         print("This car has a" + str(self.battery_size) + "-KWh battery.")
36 
37 
38 class ElectricCar(Car):
39     """电动汽车的独特"""
40 
41     def __init__(self,make,model,year):
42         """初始化父类的属性"""
43         super().__init__(make,model,year)
44 
45         # 给子类定义属性和方法
46         # self.battery_size = 70  #新属性
47         #初始化父类的属性,再初始化电动车特有的属性
48         self.battery = Battery()
49 
50     # #给子类定义属性和方法
51     # def describe_battery(self):
52     #     """打印一条描述电瓶容量的消息"""
53     #     print("This car has a " + str(self.battery_size) + "-KWh battery.")
54 
55     #重写父类的方法
56     def fill_gas_tank():
57         """电动汽车没有油箱"""
58         print("This car doesn't need a gas tank.")
59 
60 
61 my_tesla = ElectricCar('tesla','model X',2018)
62 print(my_tesla.get_descriptive_name())
63 # my_tesla.describe_battery()
64 my_tesla.battery.describe_battery()



 

执行结果:



1 2018 Tesla Model X
2 This car has a70-KWh battery.



继续将实例用作属性



class Car():
   --snip--# 将实例用作属性
class Battery():
    --snip--

  #实例2
    #打印一条消息,指出电瓶的续航里程
    def get_range(self):
        if self.battery_size == 70:
            range = 240

        elif self.battery_size == 85:
            range = 70

        msg = "This car can go approximately" + str(range)
        msg += "miles on a full charge."
        print(msg)


class ElectricCar(Car):
    --snip--

    tr

my_tesla = ElectricCar('tesla','model X',2018)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()



 

执行结果:



1 2018 Tesla Model X
2 This car has a70-KWh battery.
3 This car can go approximately240miles on a full charge.