Difference between staticmethod and classmethod

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

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

相关标签:
28条回答
  • 2020-11-21 06:48

    A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() during compilation (which happens prior to any code execution when you run a script).

    For the sake of code readability I'd avoid @staticmethod unless your method will be used for loads of work, where the nanoseconds count.

    0 讨论(0)
  • 2020-11-21 06:50

    My contribution demonstrates the difference amongst @classmethod, @staticmethod, and instance methods, including how an instance can indirectly call a @staticmethod. But instead of indirectly calling a @staticmethod from an instance, making it private may be more "pythonic." Getting something from a private method isn't demonstrated here but it's basically the same concept.

    #!python3
    
    from os import system
    system('cls')
    # %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %
    
    class DemoClass(object):
        # instance methods need a class instance and
        # can access the instance through 'self'
        def instance_method_1(self):
            return 'called from inside the instance_method_1()'
    
        def instance_method_2(self):
            # an instance outside the class indirectly calls the static_method
            return self.static_method() + ' via instance_method_2()'
    
        # class methods don't need a class instance, they can't access the
        # instance (self) but they have access to the class itself via 'cls'
        @classmethod
        def class_method(cls):
            return 'called from inside the class_method()'
    
        # static methods don't have access to 'cls' or 'self', they work like
        # regular functions but belong to the class' namespace
        @staticmethod
        def static_method():
            return 'called from inside the static_method()'
    # %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %
    
    # works even if the class hasn't been instantiated
    print(DemoClass.class_method() + '\n')
    ''' called from inside the class_method() '''
    
    # works even if the class hasn't been instantiated
    print(DemoClass.static_method() + '\n')
    ''' called from inside the static_method() '''
    # %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %   %
    
    # >>>>> all methods types can be called on a class instance <<<<<
    # instantiate the class
    democlassObj = DemoClass()
    
    # call instance_method_1()
    print(democlassObj.instance_method_1() + '\n')
    ''' called from inside the instance_method_1() '''
    
    # # indirectly call static_method through instance_method_2(), there's really no use
    # for this since a @staticmethod can be called whether the class has been
    # instantiated or not
    print(democlassObj.instance_method_2() + '\n')
    ''' called from inside the static_method() via instance_method_2() '''
    
    # call class_method()
    print(democlassObj.class_method() + '\n')
    '''  called from inside the class_method() '''
    
    # call static_method()
    print(democlassObj.static_method())
    ''' called from inside the static_method() '''
    
    """
    # whether the class is instantiated or not, this doesn't work
    print(DemoClass.instance_method_1() + '\n')
    '''
    TypeError: TypeError: unbound method instancemethod() must be called with
    DemoClass instance as first argument (got nothing instead)
    '''
    """
    
    0 讨论(0)
  • 2020-11-21 06:51

    Basically @classmethod makes a method whose first argument is the class it's called from (rather than the class instance), @staticmethod does not have any implicit arguments.

    0 讨论(0)
  • 2020-11-21 06:52

    Analyze @staticmethod literally providing different insights.

    A normal method of a class is an implicit dynamic method which takes the instance as first argument.
    In contrast, a staticmethod does not take the instance as first argument, so is called 'static'.

    A staticmethod is indeed such a normal function the same as those outside a class definition.
    It is luckily grouped into the class just in order to stand closer where it is applied, or you might scroll around to find it.

    0 讨论(0)
  • 2020-11-21 06:53

    Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:

    class A(object):
        def foo(self, x):
            print "executing foo(%s, %s)" % (self, x)
    
        @classmethod
        def class_foo(cls, x):
            print "executing class_foo(%s, %s)" % (cls, x)
    
        @staticmethod
        def static_foo(x):
            print "executing static_foo(%s)" % x    
    
    a = A()
    

    Below is the usual way an object instance calls a method. The object instance, a, is implicitly passed as the first argument.

    a.foo(1)
    # executing foo(<__main__.A object at 0xb7dbef0c>,1)
    

    With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.

    a.class_foo(1)
    # executing class_foo(<class '__main__.A'>,1)
    

    You can also call class_foo using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:

    A.class_foo(1)
    # executing class_foo(<class '__main__.A'>,1)
    

    One use people have found for class methods is to create inheritable alternative constructors.


    With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:

    a.static_foo(1)
    # executing static_foo(1)
    
    A.static_foo('hi')
    # executing static_foo(hi)
    

    Staticmethods are used to group functions which have some logical connection with a class to the class.


    foo is just a function, but when you call a.foo you don't just get the function, you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument.

    a is bound to foo. That is what is meant by the term "bound" below:

    print(a.foo)
    # <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
    

    With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.

    print(a.class_foo)
    # <bound method type.class_foo of <class '__main__.A'>>
    

    Here, with a staticmethod, even though it is a method, a.static_foo just returns a good 'ole function with no arguments bound. static_foo expects 1 argument, and a.static_foo expects 1 argument too.

    print(a.static_foo)
    # <function static_foo at 0xb7d479cc>
    

    And of course the same thing happens when you call static_foo with the class A instead.

    print(A.static_foo)
    # <function static_foo at 0xb7d479cc>
    
    0 讨论(0)
  • 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',)
    
    0 讨论(0)
提交回复
热议问题