python类中的@classmethod和@staticmethod

classmethod

@classmethod修饰符对应的函数不需要实例化,无需self参数,但需要cls参数以调用类的属性、类的方法

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

@staticmethod修饰符用于标记静态方法,静态方法是一种在类中定义的方法,它与实例无关,因此可以在不创建类实例的情况下调用,从而提高代码的灵活性和可重用性。静态方法没有self参数(不需要参数self的方法都可以加上),因此它不能访问类属性和方法,

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
"""

猜你喜欢

转载自blog.csdn.net/qq_38964360/article/details/131794291
今日推荐