Python多继承三种情况
Tips:
- 知道super.__init__和类名.__init__两者的区别
- 默认对python多继承和继承有一定的基础
- 默认知道继承__mro__
Case1(基类都未考虑多继承的情况)
class Person(object):
def __init__(self, name):
self.name = name
class Human(object):
def __init__(self, sex):
self.sex = sex
class Student(Person, Human): # 基类都独立未考虑多继承情况
def __init__(self, name ,sex):
Person.__init__(self,name)
Human.__init__(self,sex)
if __name__ == '__main__':
a = Student('xiaoming','female')
print(a.name)
print(a.sex)
class Person(object):
def __init__(self, name, *args):
self.name = name
class Human(object):
def __init__(self, sex, *args):
self.sex = sex
class Student(Person, Human):
def __init__(self,name, sex):
super().__init__(name, sex)
if __name__ == '__main__':
a = Student('xiaoming', 'female')
print(a.name)
print(a.sex) # error》'Student' object has no attribute 'sex'
#这里会报错,根据mro方法解析顺序,Person被初始化后,没有继续调用super()进行初始化 Human,拿不到sex属性?(此处是我自己的理解,欢迎讨论。)
Case 2(混合继承类)
class Person(object):
def __init__(self, name):
self.name = name
class Human(object):
def __init__(self, sex, *agrs):
self.sex = sex
super().__init__(*agrs)
class Student(Human, Person): # 顺序必须对,不然Person不能被初始化
def __init__(self,sex, name):
super().__init__(sex, name)
if __name__ == '__main__':
a = Student( 'female', 'xiaoming')
print(a.name)
print(a.sex)
Case 3(多继承设计类)
class Person(object):
def __init__(self, name,*args):
self.name = name
super().__init__(*args)
class Human(object):
def __init__(self, sex, *args):
self.sex = sex
super().__init__()
class Student(Person, Human):
def __init__(self, name, sex):
super().__init__(name, sex)
if __name__ == '__main__':
a = Student( 'female', 'xiaoming')
print(a.name)
print(a.sex)