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()
運(yùn)行報(bào)錯(cuò):
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
那么要怎么在子類(lèi)中調(diào)用父類(lèi)的方法呢:
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++有點(diǎn)類(lèi)似,不像java那樣所有的方法都是某個(gè)類(lèi)的屬性,由于有全局變量,所以在子類(lèi)中調(diào)用父類(lèi)的方法必須使用self