在Python中,类里的变量通常被称为属性。使用类属性时,你可以遵循以下步骤:
定义类属性:
在类定义内部,你可以直接为属性赋值。这些属性通常在类的所有实例之间共享。
class MyClass:attribute1 = "Shared Value"
访问类属性:
你可以通过类名直接访问类属性,或者通过类的实例访问。
通过类名访问类属性print(MyClass.attribute1) 输出 "Shared Value"通过类的实例访问类属性instance = MyClass()print(instance.attribute1) 输出 "Shared Value"
修改类属性:
你可以通过类名或实例修改类属性。所有实例都会看到这个变化。

通过类名修改类属性MyClass.attribute1 = "New Shared Value"print(MyClass.attribute1) 输出 "New Shared Value"通过实例修改类属性instance.attribute1 = "Another New Shared Value"print(instance.attribute1) 输出 "Another New Shared Value"print(MyClass.attribute1) 输出 "Another New Shared Value"
使用`self`关键字:
在类的实例方法中,你可以使用`self`关键字来引用实例的属性。
class MyClass:def __init__(self):self.attribute2 = "Instance Specific Value"def print_attribute(self):print(self.attribute2)创建类的实例instance = MyClass()通过实例的方法打印属性instance.print_attribute() 输出 "Instance Specific Value"
请注意,类属性与实例属性不同。实例属性是每个实例独有的,需要通过`self`关键字在方法内部引用。类属性是属于类的,所有实例共享。
