问题描述
我通过调用构造函数中的函数运行下面的代码
第一 -
>>> 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 $ b $由
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')
回溯(最近一次调用):
在< module>中第1行的文件< stdin&
文件< stdin>,第4行,在__init__
NameError:全局名称'printName'未定义
我可以不在构造函数中调用函数吗?和类似代码的执行偏差?
注意:我忘了使用self(ex:self.printName() )。
解决方案您需要调用
self.printName
因为你的函数是一个属于PrintName类的方法。
或者,因为你的printname函数不需要依赖对象状态,你可以只是一个模块
class PrintName:
def __init __(self,value):
self._value =值
printName(self._value)
def printName(value):
for c in value:
print c
I ran the code below, by calling the function in the constructor
First --
>>> 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
Once again I run this and I get this
>>> 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
Can I not call a function in the constructor? and whay a deviation in the execution of similar code?
Note: I forgot to call a function local to the class, by using self (ex: self.printName()). Apologize for the post.
解决方案You need to call
self.printName
since your function is a method belonging to the PrintName class.Or, since your printname function doesn't need to rely on object state, you could just make it a module level function.
class PrintName: def __init__(self, value): self._value = value printName(self._value) def printName(value): for c in value: print c
这篇关于在构造函数中调用函数时获取NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!