Python | 继承

本文目录:

一、继承定义

二、继承关系结构图

三、子类重写父类

四、多继承

一、继承定义

  类似基因的继承,在创建类时,该类可以从另一个或另几个类那里继承变量和方法新建的类是子类,

  被继承的是父类注意子类能继承父类的变量和方法父类的私有属性不能被继承

class Animal:
    we_are = "Animal"
    def eat(self):
        print("动物会吃...")


class Cat(Animal):
    pass

cat = Cat()
print(cat.we_are)
cat.eat()


"""
执行程序,会打印:
Animal
动物会吃...
"""

二、继承关系结构图

  当一个类有多个父类时,或几个类存在复杂的继承关系时,可以通过 类名.__mro__ 查看继承关系链

class Animal():
    pass


class Cat(Animal):
    pass


class Duanmao(Cat):
    pass


print(Duanmao.__mro__)
# (<class '__main__.Duanmao'>, <class '__main__.Cat'>, <class '__main__.Animal'>, <class 'object'>)

print(Cat.__mro__)
# (<class '__main__.Cat'>, <class '__main__.Animal'>, <class 'object'>)

三、子类重写父类

  1. 当父类的方法不能满足子类的使用时,子类可以重写父类方法,重写后会将父类的方法覆盖掉。

  在pycharm中重写后,行号旁边会出现一个圈儿,方便查看

 1 class Animal():
 2     def eat(self):
 3         print("animal eat")
 4 
 5 
 6 class Cat(Animal):
 7     def eat(self):
 8         print("fish")
 9 
10 
11 c = Cat()
12 c.eat()  # 打印 fish

  2. 但通常,重写只是在父类方法的基础上加一部分内容,此时需要 调用父类被覆盖的实例方法

 1 class Animal():
 2     def eat(self):
 3         print("animal eat")
 4 
 5 
 6 class Cat(Animal):
 7     def eat(self):
 8         print("fish")
 9         # 调用父类被覆盖的实例方法
10         # 格式一:父类名.方法名(对象)
11         Animal.eat(self)  # 是self调用的,对象就是self
12         # 格式二:super(本类名,对象).方法名()
13         super(Cat, self).eat()
14         # 格式三:super().方法名()   优先记忆
15         super().eat()
16         super().hello()
17 
18     def __str__(self):
19         """重写object类中的__str__方法"""
20         print(super().__str__())  # 打印 <__main__.Cat object at 0x10c7d6ba8>  
21         return "hhhh"
22 
23 
24 c = Cat()
25 c.eat()  # 打印 fish
26 print(c)  # 打印 hhhh

四、多继承

   Python可以使用多继承,但仍然推荐使用单继承,这样编程思路更加清晰。

  当一个子类有多个父类时,若父类中有相同的方法或变量,排在前面的会将后面的覆盖掉。

 1 class Father():
 2     def sing(self):
 3         print("爸爸会唱歌")
 4 
 5     def dance(self):
 6         print("爸爸不会跳舞")
 7 
 8 
 9 class Mother():
10     def sing(self):
11         print("妈妈不会唱歌")
12 
13     def dance(self):
14         print("妈妈会跳舞")
15 
16 
17 class Child(Father, Mother):
18     def sing(self):
19         # Father(self).sing()
20         Father.sing(self)  # self 调用了Father中的sing方法
21 
22         Mother.dance(self)
23 
24 
25 c = Child()
26 c.dance() 
27 # print(c.__mro__)  错啦
28 print(Child.__mro__)
29 """
30 打印:
31 爸爸不会跳舞
32 (<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class 'object'>)
33 """

  

  首先继承写在前面的类,根据__mro__的打印结果:Father覆盖了Mother中的同名方法,
  但可以用Child类中写的形式,随意调用各个父类中的方法
  其实是 "三、子类重写父类" 文件中的第一种调用父类被覆盖的实例方法

 【学习笔记,仅用于个人记录和交流】
原文地址:https://www.cnblogs.com/ykit/p/11245702.html