Tro*_*lli 0 python inheritance
有人可以解释为什么我收到错误:
global name 'helloWorld' is not defined
Run Code Online (Sandbox Code Playgroud)
执行以下操作时:
class A:
def helloWorld():
print 'hello world'
class B(A):
def displayHelloWorld(self):
helloWorld()
class Main:
def main:
b = B()
b.displayHelloWorld()
Run Code Online (Sandbox Code Playgroud)
我已经习惯了java,其中B类显然会有一个A类方法"helloWorld"的副本,因此这个代码在执行main时运行正常.然而,这似乎认为B类没有任何称为"helloWorld"的方法
在helloWorld()之前缺少自我.self关键字表示这是一个实例函数或变量.当B类继承A类时,现在可以使用self.classAfunction()它们在B类中实现的方式访问A类中的所有函数.
class A():
def helloWorld(self): # <= missing a self here too
print 'hello world'
class B(A):
def displayHelloWorld(self):
self.helloWorld()
class Main():
def main(self):
b = B()
b.displayHelloWorld()
Run Code Online (Sandbox Code Playgroud)