在构造函数中调用函数时出现 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
Can I not call a function in the constructor?类似代码的执行为何会出现偏差?
注意:我忘记使用 self(例如:self.printName())调用类的本地函数。为该帖子道歉。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要调用 self.printName ,因为您的函数是属于 PrintName 类的方法。
或者,由于您的 printname 函数不需要依赖于对象状态,因此您可以将其设为模块级函数。
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.
而不是
您想要的,因为您在父作用域中有另一个函数
printName
。它可能第一次起作用,
Instead of
you wanted
It probably worked the first time because you had another function
printName
in a parent scope.您想要的是
__init__
中的self.printName(self._value)
,而不仅仅是printName(self._value)
。What you want is
self.printName(self._value)
in__init__
, not justprintName(self._value)
.我知道这是一个老问题,但我只是想补充一点,您也可以使用类名并传递 self 作为第一个参数来调用该函数。
不知道你为什么想要这样做,因为我认为这可能会让事情变得不那么清楚。
有关详细信息,请参阅 python 手册的第 9 章:
9.3.4。方法对象
I know this is an old question, but I just wanted to add that you can also call the function using the Class name and passing self as the first argument.
Not sure why you'd want to though, as I think it might make things less clear.
See Chapter 9 of the python manuals for more info:
9.3.4. Method Objects