6.2 继承
- 继承就是一个类可以获得另外一个类中的成员属性和成员方法
- 作用: 减少代码,增加代码的复用功能,同时可以设置类与类直接的关系
- 继承与被继承的概念:
- 被继承的类叫父类,也叫基类,也叫超类
- 用与继承的类,叫子类,也叫派生类
- 继承与被继承一定存在一个 is-a 关系
- 继承的特征
- 所有的类都继承自object类,即所有的类都是object类的子类
- 子类一旦继承父类,则可以使用父类中除私有成员外的所有内容
- 子类继承父类后并没有将父类成员完全赋值到子类中,而是通过引用关系访问调用
- 子类中可以定义独有的成员属性和方法
- 子类中定义的成员和父类成员如果相同,则优先使用子类成员
- 子类如果想扩充父类的方法,可以在定义新方法的同时访问父类成员来进行代码重用
可以使用 [父类名.父类成员] 的格式来调用父类成员,也可以使用[super().父类成员]的
格式来调用
- 继承变量函数的查找顺序问题
- 优先查找自己的变量
- 没有则查找父类
- 构造函数如果本类中没有定义,则自动查找调用父类构造函数
- 如果本类有定义,则不再继续向上查找
- 构造函数
- 是一类特殊的函数,在类进行实例化之前进行调用
- 如果定义了构造函数,则实例化时使用构造函数,不查找父类构造函数
- 如果没定义,则自动查找父类构造函数
- 如果子类没定义,父类的构造函数带参数,则构造对象时的参数应该按父类参数构造
- super
- super不是关键字,而是一个类
- super的作用是获取MRO(MethodResolutionOrder)列表中的第一个类
- super与父类直接没任何实质性关系,但通过super可以调用到父类
- super使用两个方法,常见在构造函数中调用父类的构造函数
- 单继承和多继承
- 单继承:每个类只能继承一个类
- 多继承:每个类允许继承多个类
- 单继承和多继承的优缺点
- 单继承:
- 传承有序逻辑清晰语法简单隐患少
- 功能不能无限扩展,只能在当前唯一的继承链中扩展
- 多继承:
- 菱形继承/钻石继承问题
- 多个子类继承自同一个父类,这些子类又被同一个类继承,
于是继承关系图形成一个菱形图谱
- MRO
- 关于多继承的MRO
- MRO就是多继承中,用于保存继承顺序的一个列表
- python本身采用C3算法来多继承的菱形继承来进行计算的结果
- MRO列表的计算原则:
- 子类永远在父类前面
- 如果多个父类,则根据继承语法中括号内类的书写顺序存放
- 如果多个类继承了同一个父类,孙子类中只会选取继承语法
括号中第一个父类的父类
- 构造函数
- 在对象进行实例化的时候,系统自动调用的一个函数叫构造函数,通常此函数
用来对实例化对象进行初始化,顾名
- 构造函数一定要有,如果没有,则自动向上查找,按照MRO顺序,直到找到为止
class Person():
name = "NoName"
age = 18
__score = 0
_petname = "sec"
def sleep(self):
print("Sleeping ... ...")
class Teacher(Person):
teacher_id = "9527"
def make_test(self):
print("attention")
t = Teacher()
print(t.name)
print(t._petname)
t.sleep()
print(t.teacher_id)
t.make_test()
NoName
sec
Sleeping ... ...
9527
attention
class Person():
name = "NoName"
age = 18
__score = 0
_petname = "sec"
def sleep(self):
print("Sleeping ... ...")
class Teacher(Person):
teacher_id = "9527"
name = "DaNa"
def make_test(self):
print("attention")
t = Teacher
print(t.name)
DaNa
class Person():
name = "NoName"
age = 18
__score = 0
_petname = "sec"
def sleep(self):
print("Sleeping ... ...")
def work(self):
print("make some money")
class Teacher(Person):
teacher_id = "9527"
name = "DaNa"
def make_test(self):
print("attention")
def work(self):
super().work()
self.make_test()
t = Teacher()
t.work()
make some money
attention
class Dog():
def __init__(self):
print("I am init in dog")
kaka = Dog()
I am init in dog
class Animel():
pass
class PaxingAni(Animel):
pass
class Dog(PaxingAni):
def __init__(self):
print("I am init in dog")
kaka = Dog()
I am init in dog
class Animel():
def __init__(self):
print("Animel")
class PaxingAni(Animel):
def __init__(self):
print("Paxing Dongwu")
class Dog(PaxingAni):
def __init__(self):
print("I am init in dog")
kaka = Dog()
class Cat(PaxingAni):
pass
c = Cat()
I am init in dog
Paxing Dongwu
class Animel():
def __init__(self):
print("Animel")
class PaxingAni(Animel):
def __init__(self, name):
print("Paxing Dongwu {0}".format(name))
class Dog(PaxingAni):
def __init__(self):
print("I am init in dog")
d = Dog()
class Cat(PaxingAni):
pass
c = Cat()
I am init in dog
TypeError Traceback (most recent call last)
<ipython-input-29-35e195f59e34> in <module>
22 # 此时,由于Cat没有构造函数,则向上查找
23 # 因为PaxingAni的构造函数需要两个参数,实例化的时候给了一个,报错
TypeError: __init__() missing 1 required positional argument: 'name'
class Animel():
def __init__(self):
print("Animel")
class PaxingAni(Animel):
pass
class Dog(PaxingAni):
pass
d = Dog()
class Cat(PaxingAni):
pass
c = Cat()
Animel
Animel
print(type(super))
help(super)
<class 'type'>
Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super().meth(arg)
| This works for class methods too:
| class C(B):
| @classmethod
| def cmeth(cls, arg):
| super().cmeth(arg)
|
| Methods defined here:
|
| __get__(self, instance, owner, /)
| Return an attribute of instance, which is of type owner.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __self__
| the instance invoking super(); may be None
|
| __self_class__
| the type of the instance invoking super(); may be None
|
| __thisclass__
| the class invoking super()