1 # class People: #经典类 2 class People(object): #新式类 3 def __init__(self,name,age): 4 self.name=name 5 self.age=age 6 self.friends=[] 7 def eat(self): 8 print("%s is eating." % self.name) 9 def sleep(self): 10 print("%s is sleeping." % self.name) 11 class Relation(object): 12 def make_friends(self,obj): 13 print(‘%s is making friends with %s‘ %(self.name,obj.name)) 14 self.friends.append(obj) 15 obj.friends.append(self) 16 17 class Man(People,Relation): #多继承,继承顺序从左到右 18 def __init__(self,name,age,money): 19 # People.__init__(self,name,age) 20 super(Man, self).__init__(name,age) #新式类写法 21 self.property=money 22 print(‘%s has %s yuan when he was born‘%(self.name,self.property)) 23 def sleep(self): #重构 24 #People.sleep(self) #继承父类 25 super(Man,self).sleep() 26 print(‘%s is dahaning‘ % self.name) 27 class Woman(Relation,People):
28 #多继承(构造函数只需要一个),继承顺序从左到右,\
29 #第一个父类有构造函数,就不会执行第二个父类的构造函数;如果第一个父类没有构造函数,就去第二个父类中找
30 pass
1 m1=Man(‘alex‘,33,10) 2 w1=Woman(‘May‘,35) 3 4 m1.make_friends(w1) 5 print(m1.friends[0].name) 6 print(w1.friends[0].name)
Man和Woman类都继承了People和Relation两个父类,但Relation类中没有构造函数。Woman实例化时,会先去Relation类中去找构造函数,因为没找到,所以去People类中再找构造函数(从左往右的顺序)。
关于继承顺序:
在python2中新式类是按广度优先继承的,经典类是按深度优先继承的
在python3中新式类和经典类都是按广度优先继承的