我通过在构造函数中调用以下代码运行了它。
首先 -
首先 -
>>> 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())。对于这篇文章,我深感歉意。