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
网友评论