在构造函数中调用函数时出现NameError
我在构造函数里调用了下面的代码
首先 --
>>> 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 个回答
1
你原本想要的是
self.printName(self._value)
而不是
printName(self._value)
这可能第一次能正常工作是因为你在外层有另一个叫做 printName
的函数。
1
你想要的是在 __init__
里写 self.printName(self._value)
,而不是单纯的 printName(self._value)
。
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