【发布时间】:2011-08-08 21:21:52
【问题描述】:
我通过调用构造函数中的函数来运行下面的代码
首先--
>>> 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())。为帖子道歉。
【问题讨论】:
标签: python constructor