Python's class methods and static methods

  • 2020-04-02 14:26:37
  • OfStack

This article illustrates python's class methods and static methods. Share with you for your reference. Specific analysis is as follows:

Python doesn't have the static keyword in C++, so what are its static methods? What are some class methods that are rare in other languages?

The implementation of both static and class methods in python depends on python's decorator.

class MyClass: 
 
    def  method(self):
           print("method")
 
    @staticmethod
    def  staticMethod():
            print("static method")
 
     @classmethod
     def classMethod(cls):
           print("class method")

Did you notice the difference between ordinary object methods, class methods, and static methods?
Object methods have self arguments, class methods have CLS arguments, and static methods do not need these additional parameters.
There is no concept of class methods in C++


class A(object):
    "This ia A Class"     @staticmethod
    def Foo1():
        print("Call static method foo1()n")     @classmethod
    def Foo2(cls):
        print("Call class method foo2()")
        print("cls.__name__ is ",cls.__name__) A.Foo1();
A.Foo2();

The result is:
Call the static method foo1 ()

Call a class method foo2 ()
CLS. __name__ is   a.

I hope this article has helped you with your Python programming.


Related articles: