0

有人可以解释为什么我收到错误:

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”的方法

4

3 回答 3

6

在 helloWorld() 之前缺少自我。self 关键字表示这是一个实例函数或变量。当类 B 继承类 A 时,类 A 中的所有函数现在都可以self.classAfunction()像在类 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()
于 2013-10-31T22:02:17.700 回答
1

您需要指出该方法来自该类 ( self.):

class B(A):
    def displayHelloWorld(self):
        self.helloWorld()

Python 在这点上与 Java 不同。您必须在 Python 中显式指定这一点,而 Java 也隐式接受。

于 2013-10-31T22:03:42.363 回答
0

我不知道此示例中使用的 python 版本是什么,但似乎语法看起来像 python3。(除了print看起来像 python2.x 的语句)

让我们假设这是python3

我会说这helloWorld是类的类方法,A它应该被称为类属性。只要此函数位于类命名空间中,就只能使用所有者类在此类外部访问它。

A.helloWorld()

或者

B.helloWorld()

或者

self.__class__.helloWorld()

在这种情况下,您不能将其称为绑定方法,因为self参数将被传递,并且一旦您的函数不期望它就会失败。

有可能只是错过了helloWorld方法A和参数self

在这种情况下,可以按如下方式调用此方法:

self.helloWorld()

或者

A.helloWorld(self)
于 2013-10-31T22:07:18.593 回答