Getting NameError when calling function in constructor

前端 未结 4 761
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题