码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习-类的继承

时间:2018-01-21 21:28:44      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:优先   实例   pen   style   pos   类的方法   tin   nbsp   init   

 1 继承:
 2 #python2 经典类是按深度优先来继承的,新式类是按广度优先来继承的
 3 #python3 经典类和新式类都是按广度优先来继承的
 4 
 5 
 6 
 7 #经典类:class People:
 8 class People(object):  #这个是新式类,多继承的时候有了改变
 9 
10     def __init__(self, name, age):
11         self.name =name
12         self.age = age
13 
14 
15     def eat(self):
16         print("%s is eating" % self.name)
17 
18 
19     def talk(self):
20         print("%s is talking" % self.name)
21 
22     def sleep(self):
23         print("%s is sleeping" % self.name)
24 
25 #多继承的示范
26 class Relation(object):
27     def make_friends(self, obj):
28         print("%s is making friends with %s" % (self.name, obj.name))
29         self.friends.append(obj)  #要用obj,这样才和另一个实例产生联系
30 
31 #子类继承
32 class Man(People, Relation):  #小括号中 一定要有父类名称,如People
33 
34     def __init__(self, name, age, sex="man"):
35 #        People().__init__(self,name, age) 第一种的初始化方法
36         super().__init__(name, age)  # superclass,super函数直接继承所有,super(Man, self)的省略
37         self.sex = sex
38         self.friends = []
39 
40     def working_hard(self):
41         print("earning money.")
42 
43     def sleep(self):   #重构了父类的方法
44         People.sleep(self)
45         print("Man %s is sleeping" % self.name)
46 
47 
48 class Woman(People, Relation):
49 
50     def __init__(self,name, age, sex = "woman"):
51         super().__init__(name, age)
52         self.sex = sex
53         self.friends = []
54 
55     def get_birth(self):
56         print("%s is giving birth to a baby." % self.name)
57 
58 
59 p1 = People("Adam", 26)
60 p1.eat()
61 print("%s is %s years old." % (p1.name, p1.age))
62 p1.sleep()
63 
64 m1 = Man("Alex", 28)
65 m1.eat()
66 m1.working_hard()
67 m1.sleep()
68 m1.make_friends(p1)
69 print(m1.friends[0].name)
70 
71 w1 = Woman("Shell", 27)
72 w1.get_birth()
73 w1.sleep()

 

Python学习-类的继承

标签:优先   实例   pen   style   pos   类的方法   tin   nbsp   init   

原文地址:https://www.cnblogs.com/Ian-learning/p/8325432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!