__init__ and arguments in Python

前端 未结 6 1340
我寻月下人不归
我寻月下人不归 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:14

    In Python:

    • Instance methods: require the self argument.
    • Class methods: take the class as a first argument.
    • Static methods: do not require either the instance (self) or the class (cls) argument.

    __init__ is a special function and without overriding __new__ it will always be given the instance of the class as its first argument.

    An example using the builtin classmethod and staticmethod decorators:

    import sys
    
    class Num:
        max = sys.maxint
    
        def __init__(self,num):
            self.n = num
    
        def getn(self):
            return self.n
    
        @staticmethod
        def getone():
            return 1
    
        @classmethod
        def getmax(cls):
            return cls.max
    
    myObj = Num(3)
    # with the appropriate decorator these should work fine
    myObj.getone()
    myObj.getmax()
    myObj.getn()
    

    That said, I would try to use @classmethod/@staticmethod sparingly. If you find yourself creating objects that consist of nothing but staticmethods the more pythonic thing to do would be to create a new module of related functions.

提交回复
热议问题