Difference between staticmethod and classmethod

后端 未结 28 2093
一整个雨季
一整个雨季 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:42

    I will try to explain the basic difference using an example.

    class A(object):
        x = 0
    
        def say_hi(self):
            pass
    
        @staticmethod
        def say_hi_static():
            pass
    
        @classmethod
        def say_hi_class(cls):
            pass
    
        def run_self(self):
            self.x += 1
            print self.x # outputs 1
            self.say_hi()
            self.say_hi_static()
            self.say_hi_class()
    
        @staticmethod
        def run_static():
            print A.x  # outputs 0
            # A.say_hi() #  wrong
            A.say_hi_static()
            A.say_hi_class()
    
        @classmethod
        def run_class(cls):
            print cls.x # outputs 0
            # cls.say_hi() #  wrong
            cls.say_hi_static()
            cls.say_hi_class()
    

    1 - we can directly call static and classmethods without initializing

    # A.run_self() #  wrong
    A.run_static()
    A.run_class()
    

    2- Static method cannot call self method but can call other static and classmethod

    3- Static method belong to class and will not use object at all.

    4- Class method are not bound to an object but to a class.

提交回复
热议问题