Difference between staticmethod and classmethod

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

    Class methods, as the name suggests, are used to make changes to classes and not the objects. To make changes to classes, they will modify the class attributes(not object attributes), since that is how you update classes. This is the reason that class methods take the class(conventionally denoted by 'cls') as the first argument.

    class A(object):
        m=54
    
        @classmethod
        def class_method(cls):
            print "m is %d" % cls.m
    

    Static methods on the other hand, are used to perform functionalities that are not bound to the class i.e. they will not read or write class variables. Hence, static methods do not take classes as arguments. They are used so that classes can perform functionalities that are not directly related to the purpose of the class.

    class X(object):
        m=54 #will not be referenced
    
        @staticmethod
        def static_method():
            print "Referencing/calling a variable or function outside this class. E.g. Some global variable/function."
    

提交回复
热议问题