Difference between @staticmethod or @classmethod

Generally speaking, to use a method of a class, you have to instantiate an object and call the method.

But with @staticmethod or @classmethod, there is no need to instantiate, and it is called directly with classname.methodname().

The advantage of them is that it is helpful to organize the code, and put some functions belonging to a certain class into that class, which looks neat and tidy.

 

Their differences:

Leng Buding saw that the writing was almost the same, but a closer look at the first few letters was different.

From the perspective of usage, @staticmethod does not need to represent the self of its own object and the cls parameter of its own class. Similar to using a function.

@classmethod also does not need the self parameter, but the first parameter should represent the cls parameter of its own class.

 

There is one more difference:

If you call some attribute methods of this class in @staticmethod, you can only directly class name.attribute name or class name.method name.

In @classmethod, because it holds the cls parameter, it can call properties of the class, methods of the class, instantiated objects, etc.

 

Look at the code to understand

 

class A(object):  
    bar = 1  
    def foo(self):  
        print 'foo'  
 
    @staticmethod  
    def static_foo():  
        print 'static_foo'  
        print A.bar  
 
    @classmethod  
    def class_foo(cls):  
        print 'class_foo'  
        print cls.bar  
        cls().foo()  
  
A.static_foo()  
A.class_foo()  

 Take a look at the output:

 

        static_foo
         1
        class_foo
         1
        foo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326541010&siteId=291194637