__init__ and arguments in Python

前端 未结 6 1450
我寻月下人不归
我寻月下人不归 2021-01-31 14:53

I want to understand arguments of the constructor __init__ in Python.

class Num:
    def __init__(self,num):
        self.n = num
    def getn(self)         


        
6条回答
  •  你的背包
    2021-01-31 15:34

    If you print(type(Num.getone)) you will get .

    It is just a plain function, and be called as usual (with no arguments):

    Num.getone() # returns 1  as expected
    

    but if you print print(type(myObj.getone)) you will get .

    So when you call getone() from an instance of the class, Python automatically "transforms" the function defined in a class into a method.

    An instance method requires the first argument to be the instance object. You can think myObj.getone() as syntactic sugar for

    Num.getone(myObj) # this explains the Error 'getone()' takes no arguments (1 given).
    

    For example:

    class Num:
        def __init__(self,num):
            self.n = num
        def getid(self):
            return id(self)
    
    myObj=Num(3)
    

    Now if you

    print(id(myObj) == myObj.getid())    
    # returns True
    

    As you can see self and myObj are the same object

提交回复
热议问题