I. Basic Concepts of Instance Attributes and Class Attributes
In Python, an attribute is a name and value associated with an object. Based on where an attribute is defined, which object it belongs to, and how it is used, common attributes can be divided into instance attributes and class attributes.
- Instance Attribute: Belongs to a specific instance and is used to store the object's own data.
- Class Attribute: Defined in the class namespace, belongs to the class object, and can be accessed through the class or an instance.
For example, in a student management system:
- Each student has their own name, age, and grades, which are suitable for definition as instance attributes.
- All students share the same school name, which is suitable for definition as a class attribute.
class Student:
# Class attribute
school = "Python Academy"
def __init__(self, name, age):
# Instance attribute
self.name = name
self.age = age
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)
print(student1.name)
print(student2.name)
print(student1.school)
print(student2.school)
Output:
Alice
Bob
Python Academy
Python Academy
The two students have different names and ages, but both can access the same class attribute school.
1. The Relationship Between Instance Attributes and Class Attributes
flowchart TD
A["Student class object"] --> B["Class namespace"]
B --> C["school attribute"]
A --> D["student1 instance"]
A --> E["student2 instance"]
D --> F["Instance namespace"]
E --> G["Instance namespace"]
F --> H["name: Alice"]
F --> I["age: 20"]
G --> J["name: Bob"]
G --> K["age: 22"]
D -.-> C
E -.-> C
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style G fill:#F6FAF7,stroke:#DCE9E0,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Special attention should be paid here: when an instance accesses a class attribute, it does not mean that the class attribute has been copied into the instance. Typically, the instance finds the attribute on the class during attribute lookup.
II. Defining and Using Instance Attributes
Instance attributes are data that belongs to a specific instance. Different instances can have attributes with the same name, but each stores its own independent attribute value.
1. Defining Instance Attributes in init()
The most common way is to define instance attributes through self in the initialization method.
class User:
def __init__(self, username, age):
self.username = username
self.age = age
user1 = User("Alice", 25)
user2 = User("Bob", 30)
print(user1.username)
print(user2.username)
print(user1.age)
print(user2.age)
Output:
Alice
Bob
25
30
Here:
self.username = username
self.age = age
means binding the parameters to attributes of the current instance.
When executing:
user1 = User("Alice", 25)
Python will set the username and age attributes for this instance.
When another instance is created, that instance gets its own attribute state.
2. Defining Attributes in Ordinary Instance Methods
Instance attributes are not necessarily defined only in __init__(); they can also be created dynamically in other instance methods.
class User:
def __init__(self, username):
self.username = username
def set_email(self, email):
self.email = email
user = User("Alice")
user.set_email("alice@example.com")
print(user.username)
print(user.email)
Output:
Alice
alice@example.com
When self.email = email is executed, if the instance does not already have an email attribute, the attribute is created.
3. Dynamically Adding Instance Attributes Outside the Class
For objects that allow attributes to be set dynamically, you can also add attributes directly through the instance.
class Product:
pass
product = Product()
product.name = "Mechanical Keyboard"
product.price = 299
product.stock = 100
print(product.name)
print(product.price)
print(product.stock)
This approach is fairly flexible, but in large projects it is usually better to manage object state through an initialization method or explicit business methods.
4. Different Instances Have Independent Attributes
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
account1 = Account("Alice", 1000)
account2 = Account("Bob", 2000)
account1.balance += 500
print(account1.balance)
print(account2.balance)
Output:
1500
2000
Modifying account1.balance does not affect account2.balance.
This is the most important characteristic of instance attributes: each instance has its own attribute bindings.
III. Defining and Using Class Attributes
Class attributes are defined in the class namespace and are usually used to hold class-level shared data.
1. Defining Class Attributes in the Class Body
class Student:
school = "Python Academy"
country = "China"
student_count = 0
print(Student.school)
print(Student.country)
print(Student.student_count)
Output:
Python Academy
China
0
Here, school, country, and student_count are all class attributes.
They are defined directly in the namespace of the Student class, not in the namespace of any particular instance.
2. Accessing Class Attributes Through the Class Name
It is recommended to use the class name to access attributes that clearly belong to the class.
class Config:
app_name = "MyApplication"
version = "1.0.0"
debug = False
print(Config.app_name)
print(Config.version)
print(Config.debug)
This style makes it clear which class the attribute belongs to.
3. Accessing Class Attributes Through an Instance
Class attributes can also be accessed through an instance.
class Student:
school = "Python Academy"
student1 = Student()
student2 = Student()
print(student1.school)
print(student2.school)
Output:
Python Academy
Python Academy
But here it is important to understand:
Accessing a class attribute through an instance does not mean the instance owns that attribute.
When the instance itself does not have an attribute of the same name, Python continues to look for the attribute in the class and its inheritance hierarchy.
4. Using Class Attributes to Record Shared Statistical Information
Class attributes can be used to record statistical data shared by all instances.
```python class Student: student_count = 0 def __init__(self, name): self.name = name Student.student_count += 1 student1 = Student("Alice") student2 = Student("Bob") student3 = Student("Charlie") print(Student.student_count) ```Output:
```text 3 ```Here, student_count is used to record the number of students created.
Note that this simple counting approach is suitable for single-process, simple object models. Global counting in multithreaded or distributed environments needs to take concurrency safety and statistical consistency into account.
IV. Where Instance Attributes and Class Attributes Are Stored
The most important thing in understanding these two kinds of attributes is to distinguish the instance namespace from the class namespace.
1. The Instance's dict
For an ordinary instance, you can use __dict__ to view the instance's own attributes.
Output:
```text {'name': 'Alice', 'age': 20} ```As you can see, the instance's __dict__ holds:
nameage
But not school.
That is because school is a class attribute; it is not automatically copied into the instance's namespace just because the instance accesses it.
2. The Class's dict
You can view the class namespace through the class's __dict__.
Output:
```text Python Academy ChinaIn addition to class attributes, the class's __dict__ also contains methods, special attributes, and so on.
For ordinary Python classes, ClassName.__dict__ usually returns a read-only mapping proxy object rather than an ordinary dictionary that can be modified directly.
3. Instance Namespace and Class Namespace
```mermaid flowchart TD A["Python Object Attribute Storage"] --> B["Instance Namespace"] A --> C["Class Namespace"] B --> D["Instance Attributes"] D --> E["name"] D --> F["age"] C --> G["Class Attributes"] C --> H["school"] C --> I["student_count"] C --> J["Methods"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style H fill:#FFF5DE,stroke:#E8D29A,color:#334155 style I fill:#FFF5DE,stroke:#E8D29A,color:#334155 style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155 linkStyle default stroke:#A3B8AC,stroke-width:1.5px ```Note that __dict__ is a common entry point for understanding how ordinary Python objects store attributes, but not all objects use the same storage mechanism. Descriptors, inheritance, __slots__, and other mechanisms all affect how attributes are actually managed.
V. Python Attribute Lookup Rules
When accessing obj.attribute, Python does not simply look in the instance's __dict__; it performs the lookup according to the object attribute access protocol.
Understanding this explains why instances can access class attributes, and why attributes with the same name can end up shadowing one another.
1. The basic order of ordinary attribute lookup
For an ordinary instance that does not define a custom __getattribute__(), attribute access roughly follows these rules:
- First check for data descriptors on the class and its inheritance hierarchy.
- Check the instance's own attributes.
- Check ordinary attributes and non-data descriptors on the class and its inheritance hierarchy.
- If
__getattr__()is defined, it is called after ordinary lookup fails. - If the attribute still cannot be found, raise
AttributeError.
Where:
- A data descriptor is usually a descriptor that defines both
__get__()and__set__()or__delete__(). - A non-data descriptor usually defines only
__get__(). - Ordinary class attributes are generally not descriptors.
So the simple idea that instance attributes take precedence over class attributes applies only to the common case of ordinary attributes; it is not the complete attribute lookup rule.
2. Ordinary instance attributes take precedence over ordinary class attributes
class Student:
name = "默认学生"
student = Student()
print(student.name)
student.name = "Alice"
print(student.name)
print(Student.name)
Output:
默认学生
Alice
默认学生
On the first access, the instance has no name, so the class attribute is read.
After executing:
student.name = "Alice"
the instance now has an attribute with the same name, so subsequent reads get the instance attribute first.
3. Attribute lookup flow
flowchart TD
A["Access obj.attribute"] --> B["Check data descriptors on the class"]
B --> C{"Data descriptor found?"}
C -->|Yes| D["Invoke descriptor logic"]
C -->|No| E["Check instance attributes"]
E --> F{"Does the instance have this attribute?"}
F -->|Yes| G["Return instance attribute"]
F -->|No| H["Check the class and its inheritance hierarchy"]
H --> I{"Attribute found?"}
I -->|Yes| J["Return class attribute or invoke descriptor"]
I -->|No| K{"Is __getattr__ defined?"}
K -->|Yes| L["Call __getattr__"]
K -->|No| M["Raise AttributeError"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FFF5DE,stroke:#E8D29A,color:#334155
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style M fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This flow is a conceptual model of ordinary object attribute access. A custom __getattribute__(), descriptors, and special object behaviors can further change the actual access process.
4. Why class attributes can be accessed by instances
class User:
role = "member"
user = User()
print(user.role)
print(user.__dict__)
Output:
member
{}
The instance itself has no role, but Python can find it in the class's namespace.
This is the basic mechanism by which an instance accesses a class attribute.
VI. Modifying instance attributes and class attributes
Instance attributes and class attributes behave differently when modified, and this is where misunderstandings most easily arise in real development.
1. Modifying a class attribute name through an instance
class Student:
school = "Python Academy"
student1 = Student()
student2 = Student()
student1.school = "AI Academy"
print(student1.school)
print(student2.school)
print(Student.school)
Output:
AI Academy
Python Academy
Python Academy
Why wasn't the class attribute modified?
Because:
student1.school = "AI Academy"
usually creates or modifies an instance attribute of the same name in the instance namespace of student1.
The class attribute Student.school has not changed.
2. Modifying a class attribute through the class name
class Student:
school = "Python Academy"
student1 = Student()
student2 = Student()
Student.school = "AI Academy"
print(student1.school)
print(student2.school)
print(Student.school)
Output:
AI Academy
AI Academy
AI Academy
Here the class attribute is modified directly, so any instance without an instance attribute of the same name will read the new value.
3. Comparison of modifying class attributes and instance attributes
| Operation | What is modified | Are other instances affected |
|---|---|---|
obj.name = value |
Attribute of the current instance | Usually not affected |
Class.name = value |
Attribute of the class | May affect instances that have no instance attribute of the same name |
obj.name += 1 |
Depends on the type of the attribute value and the operation's behavior | Requires case-by-case analysis |
Class.name += 1 |
Class attribute binding | Affects subsequent class attribute lookups |
4. Accessing the class attribute again after deleting the instance attribute
class Student:
school = "Python Academy"
student = Student()
student.school = "AI Academy"
print(student.school)
del student.school
print(student.school)
Output:
AI Academy
Python Academy
After executing del student.school, what is deleted is the instance's own attribute of the same name.
Once the instance attribute disappears, attribute lookup finds the class attribute again.
5. The complete process of modifying a class attribute
```mermaid flowchart TD A["Access student.school"] --> B["Does the instance have school?"] B -->|Yes| C["Read instance attribute"] B -->|No| D["Read class attribute"] D --> E["Execute student.school = new value"] E --> F["Create or modify instance attribute"] F --> G["Instance access returns the new value"] G --> H["Other instances still read the original class attribute"] D --> I["Execute Student.school = new value"] I --> J["Modify class attribute"] J --> K["Instances without a same-named instance attribute read the new value"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#FFF5DE,stroke:#E8D29A,color:#334155 style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style E fill:#FFF5DE,stroke:#E8D29A,color:#334155 style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155 style I fill:#FFF5DE,stroke:#E8D29A,color:#334155 style J fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155 linkStyle default stroke:#A3B8AC,stroke-width:1.5px ```7. Mutable Class Attributes and the Shared Data Trap
Class attributes can hold not only immutable objects such as strings and numbers, but also mutable objects such as lists, dictionaries, and sets.
But without an understanding of how object sharing works, it is easy to end up with unintended data sharing.
1. A class attribute holding a mutable object
class Student:
courses = []
student1 = Student()
student2 = Student()
student1.courses.append("Python")
print(student1.courses)
print(student2.courses)
print(Student.courses)
Output:
['Python']
['Python']
['Python']
Why does Python show up for both students?
Because:
courses = []
creates only one list object, and only once, at the class definition stage.
When there is no instance attribute with the same name, both student1.courses and student2.courses access the same list referenced by this class attribute.
Executing:
student1.courses.append("Python")
modifies the list object itself rather than creating a new instance attribute.
2. The in-memory relationship of a shared mutable object
```mermaid flowchart TD A["Student class"] --> B["courses class attribute"] B --> C["shared list object"] D["student1"] -.-> B E["student2"] -.-> B F["student3"] -.-> B C --> G["Python"] C --> H["Java"] style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976 style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155 style C fill:#FFF5DE,stroke:#E8D29A,color:#334155 style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155 style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155 style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155 linkStyle default stroke:#A3B8AC,stroke-width:1.5px ```Multiple instances access the same class attribute and therefore all reference the same mutable list.
3. The right way: create the list when initializing the instance
If each student should have its own course list, the list should be defined as an instance attribute.
class Student:
def __init__(self):
self.courses = []
student1 = Student()
student2 = Student()
student1.courses.append("Python")
print(student1.courses)
print(student2.courses)
Output:
['Python']
[]
Each time an instance is created, the following is executed:
self.courses = []
This creates an independent list for each instance.
4. Do not use mutable objects as shared default state
Incorrect example:
class ShoppingCart:
items = []
If each shopping cart should have its own independent list of items, this design is unsuitable.
Recommended:
class ShoppingCart:
def __init__(self):
self.items = []
5. Storing mutable objects in class attributes is not always wrong
Some data is inherently meant to be shared by all instances, for example:
- Global registries.
- Public caches.
- Plugin registration information.
- Class-level configuration mappings.
- Shared metadata.
For example: