在构造函数中调用函数时出现NameError错误

3
我通过在构造函数中调用以下代码运行了它。
首先 -
>>> class PrintName:
...    def __init__(self, value):
...      self._value = value
...      printName(self._value)
...    def printName(self, value):
...      for c in value:
...        print c
...
>>> o = PrintName('Chaitanya')
C
h
a
i
t
a
n
y
a

再次运行此代码,会得到以下结果

>>> class PrintName:
...    def __init__(self, value):
...      self._value = value
...      printName(self._value)
...    def printName(self, value):
...      for c in value:
...        print c
...
>>> o = PrintName('Hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: global name 'printName' is not defined

我能否在构造函数中不调用一个函数?为什么相似代码的执行结果会有偏差?

注意:我忘记使用self来调用类内部的一个函数(例如:self.printName())。对于这篇文章,我深感歉意。

4个回答

11
你需要调用self.printName,因为你的函数是属于PrintName类的一个方法。
或者,由于你的printname函数不需要依赖对象状态,你可以将其作为模块级别函数。
class PrintName:
    def __init__(self, value):
        self._value = value
        printName(self._value)

def printName(value):
    for c in value:
    print c

1
我知道这是一个老问题,但我想补充一下,您还可以使用类名并将self作为第一个参数来调用函数。
不确定为什么要这样做,因为我认为这可能会使事情变得不太清晰。
class PrintName:
    def __init__(self, value):
        self._value = value
        PrintName.printName(self, self._value)

    def printName(self, value):
        for c in value:
        print(c)

请参阅Python手册第9章了解更多信息: 9.3.4. 方法对象 实际上,您可能已经猜到答案:方法的特殊之处在于将对象作为第一个参数传递给函数。在我们的示例中,调用x.f()与MyClass.f(x)完全等价。通常,使用n个参数列表调用方法等同于使用在第一个参数之前插入方法对象的参数列表调用相应的函数。

1

而不是

printName(self._value)

你想要的

self.printName(self._value)

第一次可能成功是因为您在父范围中有另一个名为printName的函数。


1
你想要的是在__init__中使用self.printName(self._value),而不仅仅是printName(self._value)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接