Notes: static methods and class methods

Static methods and class methods

They are packaged in objects and staticmethod classmethod class. Define a static method has no parameters self, can be directly invoked through the class. The method defined class parameters comprising similar self, commonly named cls. The method class may be called directly by the object, but the parameters are automatically associated with the class cls.

Examples

class MyClass():

    @staticmethod
    def smeth():
        print('This is a static method')

    @classmethod
    def cmeth(cls):
        print('This is a class method of', cls)

        
# 无需实例化类
MyClass().smeth()
MyClass().cmeth()

# This is a static method
# This is a class method of <class '__main__.MyClass'>

Guess you like

Origin www.cnblogs.com/dhzg/p/11564377.html