多继承

我只是一个虾纸丫 提交于 2019-11-28 13:11:56

Python允许从多个父类继承 , 称为多重继承
class A(object):
def __init__(self, a):
print 'init A...'
self.a = a

class B(A):
def __init__(self, a):
super(B, self).__init__(a)
print 'init B...'

class C(A):
def __init__(self, a):
super(C, self).__init__(a)
print 'init C...'

class D(B, C):
def __init__(self, a):
super(D, self).__init__(a)
print 'init D...'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
多重继承通过 super()调用__init__()方法时 , A 虽然被继承了两次,但__init__()只调用一次

实例
class Person(object):
pass

class Student(Person):
pass

class Teacher(Person):
pass

class SkillMixin(object):
pass

class BasketballMixin(SkillMixin):
def skill(self):
return 'basketball'

class FootballMixin(SkillMixin):
def skill(self):(http://www.amjmh.com/v/BIBRGZ_558768/)
return 'football'

class BStudent(Student, BasketballMixin):
pass

class FTeacher(Teacher, FootballMixin):
pass


if __name__ == '__main__':
s = BStudent()
print(s.skill())
t = FTeacher()
print(t.skill())
————————————————

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!