Python类的继承的小例子
关于父类与子类的小例子
class human(object):
def __init__(self,name,eye=2,age=None):
self.name = name
self.eye = eye
self.age = age
def action(self):
print("%s有%u个eye,这个人已经%u岁了" %(self.name,self.eye,self.age))
class father(human):
namef = []
def __init__(self,name):
self.name = name
father.namef = name
def action(self):
print("我是%s,是一名父亲" %(self.name))
class son(human):
def action(self):
print("我是%s,是%s的儿子"%(self.name,father.namef))
one = human("one",2,20)
tom = father("tom")
devid = son("devid")
bob1 = father("bob1")
micheal = son("micheal")
def actiont(hm):
return hm.action()
actiont(one)
actiont(tom)
actiont(devid)
actiont(bob1)
actiont(micheal)
输出的结果为
one有2个eye,这个人已经20岁了
我是tom,是一名父亲
我是devid,是bob1的儿子
我是bob1,是一名父亲
我是micheal,是bob1的儿子
在看到这段代码时,关于输出的第三行第五行为什么是bob1的儿子始终不明白。后来找到问题所在,在namef列表中,当程序运行到bob1 = father("bob1")
时列表的值已经替换成namef的值已经成为bob1,所以在接下来的程序运行中并没有改变列表的值,即输出是bob1。