python练习六十五:类的使用实例

代码:

  1 class human():  #定义基类,包括属性和方法
  2     def __init__(self,name,eye=2,age=98,city='陕西'):  #属性值有四个,分别为name,eye,age,city
  3         self.name = name
  4         self.eye = eye
  5         self.age = age
  6         self.city = city
  7 
  8     def action(self): #基类定义的方法
  9         print('我祖籍是{},已经{}岁了,我的名字是叫{},{}眼睛还是很明亮的'.format(self.city,self.age,self.name,self.eye))
 10 
 11 class father(human):  #继承类1
 12     def __init__(self,name):
 13         super(father,self).__init__(name)  #super()方法将父类的属性值全部继承
 14         father.namef = name
 15 
 16     def action(self):
 17         super(father,self).action()
 18         print("我是{},是一名父亲" .format(self.name))
 19 
 20 class son(human): #继承类2
 21     def __init__(self,name):
 22         super(son,self).__init__(name,age=18)
 23 
 24     def action(self):
 25         super().action()
 26         print("我是{},是{}的儿子".format(self.name,father.namef))  #既然调用的father.name,就必须先实例化father类
 27 
 28 frist = human("one")
 29 frist.action()
 30 tom = father("tom")
 31 tom.action()
 32 devid = son("devid")
 33 devid.action()
 34 

执行结果:

我祖籍是陕西,已经98岁了,我的名字是叫one,2眼睛还是很明亮的
我祖籍是陕西,已经98岁了,我的名字是叫tom,2眼睛还是很明亮的
我是tom,是一名父亲
我祖籍是陕西,已经18岁了,我的名字是叫devid,2眼睛还是很明亮的
我是devid,是tom的儿子
原文地址:https://www.cnblogs.com/pinpin/p/10322607.html