Difference between staticmethod and classmethod

后端 未结 28 2197
一整个雨季
一整个雨季 2020-11-21 06:11

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

28条回答
  •  猫巷女王i
    2020-11-21 06:53

    Let me tell the similarity between a method decorated with @classmethod vs @staticmethod first.

    Similarity: Both of them can be called on the Class itself, rather than just the instance of the class. So, both of them in a sense are Class's methods.

    Difference: A classmethod will receive the class itself as the first argument, while a staticmethod does not.

    So a static method is, in a sense, not bound to the Class itself and is just hanging in there just because it may have a related functionality.

    >>> class Klaus:
            @classmethod
            def classmthd(*args):
                return args
    
            @staticmethod
            def staticmthd(*args):
                return args
    
    # 1. Call classmethod without any arg
    >>> Klaus.classmthd()  
    (__main__.Klaus,)  # the class gets passed as the first argument
    
    # 2. Call classmethod with 1 arg
    >>> Klaus.classmthd('chumma')
    (__main__.Klaus, 'chumma')
    
    # 3. Call staticmethod without any arg
    >>> Klaus.staticmthd()  
    ()
    
    # 4. Call staticmethod with 1 arg
    >>> Klaus.staticmthd('chumma')
    ('chumma',)
    

提交回复
热议问题