BitTigerio 2018-02-03
# 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中新式类和经典类都是按广度优先继承的