[英]Dealing with class inheritance in python
有人可以解释为什么我得到这个错误:
global name 'helloWorld' is not defined
执行以下命令时:
class A:
def helloWorld():
print 'hello world'
class B(A):
def displayHelloWorld(self):
helloWorld()
class Main:
def main:
b = B()
b.displayHelloWorld()
我习惯于Java,其中类B显然具有类A的方法“ helloWorld”的副本,因此在执行main时此代码可以正常运行。 但是,这似乎认为类B没有任何称为“ helloWorld”的方法
在helloWorld()之前缺少自我。 self关键字表示这是实例函数或变量。 当类B继承类A时,现在可以使用self.classAfunction()
来访问类A中的所有函数,就像它们是在类B中实现的一样。
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()
您需要指出该方法来自该类( self.
):
class B(A):
def displayHelloWorld(self):
self.helloWorld()
Python在这方面不同于Java。 您必须在Python中显式指定它,而Java也隐式接受。
我不知道此示例中使用的python版本是什么,但是语法看起来像python3。 (除了看起来像python2.x的print
语句)
让我们假设这是python3
我会说helloWorld
是A
类的类方法,应将其称为class属性。 一旦此函数位于类名称空间中,就只能使用所有者类在该类外部对其进行访问。
A.helloWorld()
要么
B.helloWorld()
要么
self.__class__.helloWorld()
在这种情况下,您不能将其称为绑定方法,因为将传递self
参数,并且一旦函数不期望它就会失败。
helloWorld
是A
方法而self
参数有可能被遗漏了
在这种情况下,可以按以下方式调用此方法:
self.helloWorld()
要么
A.helloWorld(self)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.