python多继承
# class People: #经典类 class People(object): #新式类 def __init__(self,name,age): self.name=name self.age=age self.friends=[] def eat(self): print("%s is eating." % self.name) def sleep(self): print("%s is sleeping." % self.name) class Relation(object): def make_friends(self,obj): print('%s is making friends with %s' %(self.name,obj.name)) self.friends.append(obj) obj.friends.append(self) class Man(People,Relation): #多继承,继承顺序从左到右 def __init__(self,name,age,money): # People.__init__(self,name,age) super(Man, self).__init__(name,age) #新式类写法 self.property=money print('%s has %s yuan when he was born'%(self.name,self.property)) def sleep(self): #重构 #People.sleep(self) #继承父类 super(Man,self).sleep() print('%s is dahaning' % self.name) class Woman(Relation,People<span>): <br /><br /> #多继承(构造函数只需要一个),继承顺序从左到右,\ <br /> #第一个父类有构造函数,就不会执行第二个父类的构造函数;如果第一个父类没有构造函数,就去第二个父类中找 <br /><br /> pass <br /><br />
m1=Man('alex',33,10) w1=Woman('May',35) m1.make_friends(w1) print(m1.friends[0].name) print(w1.friends[0].name)
Man和Woman类都继承了People和Relation两个父类,但Relation类中没有构造函数。Woman实例化时,会先去Relation类中去找构造函数,因为没找到,所以去People类中再找构造函数(从左往右的顺序)。
关于继承顺序:
在python2中新式类是按广度优先继承的,经典类是按深度优先继承的<br />在python3中新式类和经典类都是按广度优先继承的
相关推荐
Laozizuiku 2020-04-10
tangjikede 2020-04-30
猛禽的编程艺术 2020-04-18
lhxxhl 2020-02-14
meylovezn 2020-02-12
taiyangshenniao 2020-01-03
gaedmihx 2019-11-18
georgeandgeorge 2019-10-22
82467413 2012-06-18
程松 2019-04-08
HuangXiaoChuan 2018-01-09
wangcaipang 2012-03-04
无所畏惧 2019-06-17
ZGCdemo 2015-02-08
麋鹿麋鹿迷了路 2011-07-08
85437811 2014-03-28
linbossdeboke 2018-11-19
lookFuture 2018-11-15