在这一步中,你将学习 Python 中的类属性(class attributes)。类属性是在类内部定义的变量,由该类的所有实例(对象)共享。它们与实例属性(instance attributes)不同,实例属性是每个实例特有的。理解类属性对于设计高效且有条理的类至关重要。
-
打开你的 VS Code 编辑器。
-
在 ~/project
目录下创建一个名为 class_attributes.py
的新文件。
~/project/class_attributes.py
-
将以下代码添加到 class_attributes.py
文件中:
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
## Creating instances of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)
## Accessing the class attribute
print(dog1.species)
print(dog2.species)
## Accessing instance attributes
print(dog1.name)
print(dog2.name)
在这个例子中,species
是一个类属性,因为它是在 Dog
类内部但在任何方法之外定义的。name
和 age
是实例属性,因为它们是在 __init__
方法中定义的,并且是每个 Dog
实例特有的。
-
在终端中使用以下命令运行 class_attributes.py
脚本:
python class_attributes.py
你应该会看到以下输出:
Canis familiaris
Canis familiaris
Buddy
Lucy
如你所见,dog1
和 dog2
都共享相同的 species
值,即 "Canis familiaris"。然而,它们的 name
值不同,因为 name
是一个实例属性。
-
现在,让我们修改类属性,看看它如何影响实例:
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
## Creating instances of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)
## Accessing the class attribute
print(dog1.species)
print(dog2.species)
## Modifying the class attribute
Dog.species = "New Species"
## Accessing the class attribute again
print(dog1.species)
print(dog2.species)
-
再次运行 class_attributes.py
脚本:
python class_attributes.py
你应该会看到以下输出:
Canis familiaris
Canis familiaris
New Species
New Species
注意,当我们修改 Dog.species
时,这个更改会反映在 dog1
和 dog2
中,因为它们共享相同的类属性。