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

2015-08-12  本文已影响2360人  lovePython
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

上一篇 下一篇

猜你喜欢

热点阅读