可做长图的网站,h5制作官网,怎么做vip网站,做哪种类型网站赚钱classmethod
classmethod修饰符对应的函数不需要实例化#xff0c;无需self参数#xff0c;但需要cls参数以调用类的属性、类的方法
class A:a 10def printb(self, b):print(b)classmethoddef printa(cls):print(cls.a)print(cls().printb(5))A.printa()classmethod修饰符对应的函数不需要实例化无需self参数但需要cls参数以调用类的属性、类的方法
class A:a 10def printb(self, b):print(b)classmethoddef printa(cls):print(cls.a)print(cls().printb(5))A.printa()
10
5staticmethod
staticmethod修饰符用于标记静态方法静态方法是一种在类中定义的方法它与实例无关因此可以在不创建类实例的情况下调用从而提高代码的灵活性和可重用性。静态方法没有self参数不需要参数self的方法都可以加上因此它不能访问类属性和方法
class B:a 10def printb(self, b):print(b)staticmethoddef printxy(x, y):print(xy)print(a) # 无法调用类属性print(printb(5)) # 无法调用类方法B.printxy(1, 2)
3
NameError: name a is not defined
NameError: name printb is not defined