Getting NameError when calling function in constructor

谁都会走 提交于 2019-12-20 01:39:57

问题


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.


回答1:


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



回答2:


Instead of

printName(self._value)

you wanted

self.printName(self._value)

It probably worked the first time because you had another function printName in a parent scope.




回答3:


What you want is self.printName(self._value) in __init__, not just printName(self._value).




回答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.

class PrintName:
    def __init__(self, value):
        self._value = value
        PrintName.printName(self, self._value)

    def printName(self, value):
        for c in value:
        print(c)

See Chapter 9 of the python manuals for more info:

9.3.4. Method Objects

Actually, you may have guessed the answer: the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.



来源:https://stackoverflow.com/questions/6988779/getting-nameerror-when-calling-function-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!