继承顺序:

class (A,B,C):按左右顺序继承

1 class A():
2     pass
3 class B(A):
4     pass
5 class C(A):
6     pass
7 class D(B,C):
8     pass

广度优先:

在这种情况下,先执行D中的构造函数;若D中没有构造函数则在B中找,B中有则执行;若B没有则在C中找,若C中也没有则在A中找。在python3中,经典类和新式类都使用广度优先执行。广度优先效率比较高。

深度优先:

在这种情况下,先执行D中的构造函数;若D中没有构造函数则在B中找,B中有则执行;若B没有则在A中找,若A中也没有则在C中找。在python2中,经典类按深度优先执行;新式类是按广度优先来继承的,

经典类写法:class A:

新式类写法:class A(object):

 

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:James Tao
 4 
 5 class People(object): #父类,实际上这也是继承
 6 
 7     def __init__(self,name,age):
 8         self.name=name
 9         self.age=age
10         self.friends=[]
11 
12     def eat(self):
13         print('%s is eating...' % self.name)
14 
15     def talk(self):
16         print('%s is talking...' % self.name)
17 
18     def sleep(self):
19         print('%s is sleeping...' % self.name)
20 
21 class Relationship(object):
22 
23     def make_friends(self,obj):
24         print('%s is making friends with %s' % (self.name,obj.name))
25         self.friends.append(obj)
26 
27 class Man(People,Relationship): #子类,继承Pelple,继承多个父类:继承顺序从左到右,只执行People的init
28     #当类本身没有构造函数时,从左到右找父类的构造函数init,执行第一个有构造函数的父类的构造函数
29 
30     def __init__(self,name,age,money):#就不会调用父类的初始化了
31         #People.__init__(self,name,age) #父类的初始化要调用一遍,方法一
32         super(Man,self).__init__(name,age)#方法二,不用写多个People
33         self.money=money
34         print('%s有%s元' % (self.name,self.money))
35 
36     def piao(self): #加新功能
37         print('%s is piaoing...' % self.name)
38 
39     def sleep(self):#重构父类功能
40         People.sleep(self)
41         print('Man is sleeping...')
42 
43 class Woman(People,Relationship): #子类,继承People
44 
45     def get_birth(self):
46         print('%s is delievered to a baby' % self.name)
47 
48 man1=Man('James',23,10000)
49 man1.eat()
50 man1.sleep()
51 man1.piao()
52 
53 woman1=Woman('Penny',23)
54 woman1.get_birth()
55 
56 man1.make_friends(woman1)
57 print('%s的朋友名单有%s' % (man1.name,man1.friends[0].name))#

运行结果:

posted on 2019-01-20 23:12  研究僧桃子  阅读(109)  评论(0编辑  收藏  举报