继承父类,调用父类中的方法 分类: python 小练习 python基础学习 2014-01-10 17:54 325人阅读 评论(0) 收藏

定义的类与基类可以可以放在不同的模块,例如:

定义类 DerivedClassName,继承modname模块中的BaseClassName类
class DerivedClassName(modname.BaseClassName):


派生类定义的执行过程和基类是一样的。构造派生类对象时,就记住了基类。这在解析属性引用的时候尤其有用:如果在类中找不到请求调用的属性,就搜索基类。如果基类是由别的类派生而来,这个规则会递归的应用上去。


方法引用按如下规则解析:搜索对应的类属性,必要时沿基类链逐级搜索,如果找到了函数对象这个方法引用就是合法的。


例子中包括personel.py、little.py  两个模块,在little.py模块中没有young方法,而父类person中有该方法,则python会搜索父类中的方法,并调用该方法。


personel.py

#coding:utf-8

class person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def young(self,food="milk"):
        print 'I am young,i wanna drink %s' % food
    def adult(self):
        print 'I will on a trip,will you follow me?'

little.py

#coding:utf-8

from personel import person

class baby(person):
    def __init__(self,birth,name,age):
        self.birth = birth
        person.__init__(self,name,age)

    def drinking(self):
        self.young("juice")
        print "I need some pies,too"

    def party(self):
        print "my birth day %s is on the way,welcome to my party" % self.birth

if __name__=="__main__":
    bb = baby("February",'little sam',2)
    bb.drinking()
    bb.party()


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/think1988/p/4627969.html