标签:
继承:是python中类与类之间的关系,主要是用已经写好的类来产生新类,子类会从父类中继承属性或方法!
1 # -*- coding: utf-8 -*- 2 class Person: 3 def __init__(self,race,age,height,sex): 4 self.race = race 5 self.age = age 6 self.height = height 7 self.sex = sex 8 def talk(self,language): 9 self.language = language 10 if language == ‘English‘: 11 print ‘I am seapking %s‘ % self.language 12 else: 13 print "I don‘t konw I‘m speaking what language now!" 14 15 16 class PersonDemo(Person): #继承父类 17 def __init__(self,name,country,like,race,age,height,sex): 18 Person.__init__(self,race,age,height,sex) #继承父类属性 19 self.name = name 20 self.country = country 21 self.likes = like 22 23 def infos(self): 24 print ‘‘‘this is my informaion: 25 姓名: %s 26 年龄: %s 27 肤色: %s 28 身高: %s 29 性别: %s 30 国籍: %s 31 爱好: %s 32 ‘‘‘ %(self.name,self.age,self.race,self.height,self.sex,self.country,self.likes) 33 34 #实例化对象 35 p = PersonDemo(‘但丁‘,‘CN‘,‘games‘,‘Yellow‘,27,177,‘男‘) 36 #调用子类本身的方法 37 p.infos() 38 #调用从父类中继承的方法 39 p.talk(‘English‘)
所得结果:
this is my informaion: 姓名: 但丁 年龄: 27 肤色: Yellow 身高: 177 性别: 男 国籍: CN 爱好: games I am seapking English
编写一个子类只需要它指定其父类即可,剩下的和普通类基本类似
标签:
原文地址:http://www.cnblogs.com/hexj0623/p/4654842.html