class MyClass:
class_variable = 0
def __init__(self, value):
self.value = value
MyClass.class_variable += 1
@classmethod
def get_class_variable(cls):
# cls refers to the class itself, not an instance of the class
return cls.class_variable
# 创建类的实例
obj1 = MyClass(10)
obj2 = MyClass(20)
# 调用类方法,不需要实例化对象
print(MyClass.get_class_variable()) # 输出: 2
@classmethod 是一个装饰器,用于定义类方法。类方法的第一个参数是 cls,它代表类本身,而不是类的实例。get_class_variable 是一个类方法,它可以访问和修改类变量 class_variable,并且可以通过类名 MyClass 直接调用。上一篇:python nltk
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站