Getting NameError when calling function in constructor

前端 未结 4 720
粉色の甜心
粉色の甜心 2021-01-21 07:31

I ran the code below, by calling the function in the constructor

First --

>>> class PrintName:
...    def __init__(self, value):
...      self.         


        
相关标签:
4条回答
  • 2021-01-21 07:36

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

    0 讨论(0)
  • 2021-01-21 07:44

    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.

    0 讨论(0)
  • 2021-01-21 07:45

    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.

    0 讨论(0)
  • 2021-01-21 07:48

    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
    
    0 讨论(0)
提交回复
热议问题