美文网首页
Python中子类如何调用父类的方法

Python中子类如何调用父类的方法

作者: lovePython | 来源:发表于2015-08-12 17:21 被阅读2360次
class FooParent(object):
    def __init__(self):
        print 'Parent'
    def test(self):
        print 'foo parent'

class FooChild(FooParent):
    def bar(self):
        test()

if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar()

运行报错:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    fooChild.bar() 
  File "test.py", line 9, in bar
    test() 
NameError: global name 'test' is not defined

那么要怎么在子类中调用父类的方法呢:

class FooParent(object):
    def __init__(self):
        print 'Parent'
    def test(self):
        print 'foo parent'

class FooChild(FooParent):
    def bar(self):
        self.test()
        FooParent.test(self)
        super(FooChild, self).test()


if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar()

python跟C++有点类似,不像java那样所有的方法都是某个类的属性,由于有全局变量,所以在子类中调用父类的方法必须使用self

相关文章

网友评论

      本文标题:Python中子类如何调用父类的方法

      本文链接:https://www.haomeiwen.com/subject/xwwiqttx.html