码迷,mamicode.com
首页 > 其他好文 > 详细

类的继承

时间:2017-10-27 23:53:31      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:bsp   style   父类   blog   alt   经典   多继承   包含   属性   

#by zxq
#继承:在一个大的类下面包含小的类,通用的属性和方法不用再写,
# 继承的主要作用是为了节省代码
技术分享
 1 #class People:#经典类的写法
 2 class People(object):#新式类的写法,推荐使用
 3     def __init__(self,name,age):
 4         self.name=name
 5         self.age=age
 6     def eat(self):
 7         print("%s在享受美食"%self.name)
 8     def talk(self):
 9         print("%s在作诗"%self.name)
10     def sleep(self):
11         print("%s在睡觉"%self.name)
12 class Man(People):
13     def __init__(self,name,age,beard):
14         #People.__init__(self,name,age)#继承了父类People,当多继承时比较麻烦
15         super(Man,self).__init__(name,age)#当父类改变名字时,不用改了,推荐写法
16         self.beard=beard
17     def grow_beard(self):
18         print("%s%s岁的胡子%s厘米长"%(self.name,self.age,self.beard))
19     def sleep(self):
20         People.sleep(self)#重构的方法
21         print("男人在休息")
22 m1=Man("李白","35","6")
23 m1.eat()
24 m1.talk()
25 m1.grow_beard()
26 class Woman(People):
27     def get_birth(self):
28         print("%s在生孩子"%self.name)
29 w1=Woman("卫子夫",19)
30 w1.get_birth()
View Code

 

类的继承

标签:bsp   style   父类   blog   alt   经典   多继承   包含   属性   

原文地址:http://www.cnblogs.com/pythonkids/p/7745587.html

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