@classmethod and @staticmethod in python classes

classmethod

The function corresponding to the @classmethod modifier does not need to be instantiated, no self parameter is required, but the cls parameter is required to call the attributes and methods of the class

class A:
    a = 10
    def printb(self, b):
        print(b)

    @classmethod
    def printa(cls):
        print(cls.a)
        print(cls().printb(5))

A.printa()


"""
10
5
"""

staticmethod

The @staticmethod modifier is used to mark a static method. A static method is a method defined in a class that has nothing to do with an instance, so it can be called without creating a class instance, thereby improving code flexibility and reusability. Static methods do not have self parameters (methods that do not require self parameters can be added), so it cannot access class properties and methods,

class B:
    a = 10
    def printb(self, b):
        print(b)

    @staticmethod
    def printxy(x, y):
        print(x+y)
        print(a)  # 无法调用类属性
        print(printb(5))  # 无法调用类方法

B.printxy(1, 2)


"""
3
NameError: name 'a' is not defined
NameError: name 'printb' is not defined
"""

Guess you like

Origin blog.csdn.net/qq_38964360/article/details/131794291