第六周练习 part2 --- 继承

 1 # class People:  # 经典类
 2 class People(object):  # 新式类, super 也是新式类的写法
 3     def __init__(self,name,age):
 4         self.name = name
 5         self.age = age
 6         self.friends = []
 7         print("class People下的__init__ is running.")
 8 
 9     def eat(self):
10         print("%s is eating..." % self.name)
11 
12     def talk(self):
13         print("%s is talking..." % self.name)
14 
15     def sleep(self):
16         print("%s is sleeping..." % self.name)
17 
18 
19 class Relation(object):
20     def __init__(self, name):
21         self.name = name
22         print(self.name)
23 
24     def make_friends(self, somebody):
25         print('%s is making friends with %s.' % (self.name, somebody.name))
26         self.friends.append(somebody)  # 将这个人的地址存在 People 下的 friends 里,真正建立起联系
27 
28 
29 # class Man(Relation, People):  # 调用父类是只走第一个位置的类的,Relation 里的__init__参数不对,那就会报错
30 class Man(People, Relation):
31     def __init__(self, name, age, money):
32 
33         # People.__init__(self, name, age)  # 继承自 People. or...
34         super(Man, self).__init__(name, age)  # 与上句作用相同
35 
36         self.money = money
37         print('class Man 下的 __init__ is running.')
38 
39     def piao(self):
40         print("%s is piaoing ..... 20s later....done." % self.name)
41 
42     # Overrides the sleep method in Class People
43     def sleep(self):
44         People.sleep(self)  # 调用重构前的功能
45         print("man is sleeping ")  # 添加新功能
46 
47 
48 class Woman(People, Relation):
49     def __init__(self, name, age, weight):
50         super(Woman, self).__init__(name, age)
51         print('class Woman 下的 __init__ is running.')
52 
53     def eat(self):
54         print('%s is eating.' % self.name)
55 
56 t = Man('Tony', '23', 22334)  # 此步叫初始化,会将参数传给相应类中的__init__()并运行
57 p = Woman('Sara', '23', 37822)
58 # t.sleep()
59 t.make_friends(p)
60 print(t.friends[0].name)  # 存地址而不直接存名字,好处是即使改了名字,也仍能指到同一个人

猜你喜欢

转载自www.cnblogs.com/lief/p/9059637.html
今日推荐