I. What Is Encapsulation
Encapsulation is one of the core concepts of object-oriented programming. It means organizing data and the methods that operate on that data into the same object, and controlling external access to the internal state through a well-defined interface.
Encapsulation mainly solves three problems:
- Hiding the internal implementation: External code does not need to know how an object stores and processes data internally.
- Protecting object state: It prevents external code from modifying attributes at will and breaking the object's data consistency.
- Providing a unified access point: Validation, conversion, logging, and similar operations are performed through method or attribute interfaces.
For example, a bank account object should not allow external code to freely set the balance to a negative number; instead, the balance should be maintained through deposit and withdrawal operations.
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("存款金额必须大于 0")
self.balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("取款金额必须大于 0")
if amount > self.balance:
raise ValueError("余额不足")
self.balance -= amount
Usage example:
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.balance) # 1300
Here the account data and the business operations are organized in the same class, with changes to the balance controlled through the deposit and withdrawal methods.
However, the balance in the example can still be modified directly from outside:
account.balance = -10000
This shows that simply placing data and methods in the same class does not automatically protect the data. Python also provides attribute access control mechanisms.
II. Attribute Access Permissions in Python
Unlike languages such as Java and C++, Python does not implement strict member access control through the public, protected, and private keywords.
Instead, Python mainly uses naming conventions to express the intended access level of attributes.
There are three common ways to name attributes:
| Naming convention | Example | Conventional meaning |
|---|---|---|
| Public attribute | name |
Can be accessed from outside |
| Protected attribute | _age |
For internal use; external access should be cautious |
| Private attribute | __salary |
Name mangling reduces the likelihood of direct external access |
1. Public Attributes
Public attributes are defined with ordinary names and can be accessed directly from both inside and outside the class.
class User:
def __init__(self, name):
self.name = name
user = User("Alice")
print(user.name)
user.name = "Bob"
print(user.name)
Output:
Alice
Bob
Public attributes are suitable for data that has no special validation requirements and is allowed to be read and modified directly from outside.
2. Protected Attributes
Protected attributes usually use a single leading underscore.
class User:
def __init__(self, name, age):
self.name = name
self._age = age
user = User("Alice", 25)
print(user._age)
Although _age can be accessed normally, the single underscore expresses a convention:
- The attribute is part of the class's internal implementation.
- External code should not depend on it casually.
- Subclasses may use it as needed.
- If the attribute is changed in the future, external code that relies on the internal implementation may be affected.
For example:
class Employee:
def __init__(self, salary):
self._salary = salary
def calculate_bonus(self):
return self._salary * 0.1
Here _salary represents salary data intended for internal use.
Note that a single underscore does not prevent external access, nor does it trigger any special access control mechanism in Python.
3. Private Attributes
A double underscore prefix is usually used to indicate attributes that the class does not want to be accessed directly from outside.
class User:
def __init__(self, username, password):
self.username = username
self.__password = password
user = User("alice", "123456")
print(user.username)
Directly accessing a private attribute:
print(user.__password)
will produce an error similar to:
AttributeError: 'User' object has no attribute '__password'
But this does not mean that Python truly prohibits access to that attribute.
Behind this is the name mangling mechanism (Name Mangling).
III. Name Mangling Mechanism
Name mangling is an important mechanism Python uses to handle double-underscore attributes.
When an attribute name in a class definition begins with at least two leading underscores and does not end with two or more underscores, Python rewrites it into a form that includes the class name.
For example:
class User:
def __init__(self):
self.__password = "secret"
In a class definition, the attribute name:
__password
will be rewritten as:
_User__password
Therefore, it can be accessed through the rewritten name:
user = User()
print(user._User__password)
Output:
secret
This shows that double underscores are not absolute private access control, but rather a name-collision avoidance mechanism.
1. Rules of Name Mangling
Name mangling can be understood according to the following rules:
Original name: __attribute
Class name: User
Mangled name: _User__attribute
Specific rules:
- Only names that meet the conditions in a class definition context are processed.
- The name begins with at least two underscores.
- The name must not end with two or more underscores.
- Leading underscores in the class name are removed before it participates in mangling.
- The mangled name usually begins with a single underscore.
For example:
class User:
def __init__(self):
self.__name = "Alice"
self.__password__ = "secret"
self._age = 25
Corresponding relationships:
| Original Name | Mangled? | Actual Name |
|---|---|---|
__name |
Yes | _User__name |
__password__ |
No | __password__ |
_age |
No | _age |
Special methods or special attributes that begin and end with double underscores are not mangled according to the rules for ordinary private names.
2. Purpose of Name Mangling
The most important use of name mangling is to prevent subclasses from accidentally overriding internal attributes of parent classes.
class Parent:
def __init__(self):
self.__value = "parent"
def show(self):
print(self.__value)
class Child(Parent):
def __init__(self):
super().__init__()
self.__value = "child"
obj = Child()
obj.show()
Output:
parent
Why is it not child?
Because __value in the parent class is mangled to _Parent__value, and __value in the child class is mangled to _Child__value.
They are two different attribute names, so they do not override each other.
You can use vars() to observe the object's actual attributes:
print(vars(obj))
Possible output:
{
'_Parent__value': 'parent',
'_Child__value': 'child'
}
Name mangling is particularly suitable for the following scenarios:
- Parent classes need to protect internal attributes to prevent accidental overriding by subclasses.
- Frameworks or libraries need to reduce the probability of internal name conflicts.
- A class contains implementation details that should not become part of the public interface.
But it cannot replace security mechanisms. For sensitive information such as passwords and keys, you cannot rely on double underscores to protect data.
IV. Basic Implementation of Attribute Access Control
If an attribute needs validation when it is read or modified, it should not simply be exposed as an ordinary public attribute.
Python provides several ways to implement attribute access control:
- Use ordinary methods to control reading and modification.
- Use
propertyto wrap methods as attributes. - Use descriptors to implement reusable attribute management logic.
Among these, property is the most common way to control attributes.
1. Using Getter and Setter Methods
Getters are used to read attributes, and setters are used to modify attributes.
class Person:
def __init__(self, age):
self._age = age
def get_age(self):
return self._age
def set_age(self, value):
if not isinstance(value, int):
raise TypeError("年龄必须是整数")
if value < 0:
raise ValueError("年龄不能为负数")
self._age = value
Usage example:
person = Person(20)
print(person.get_age())
person.set_age(25)
print(person.get_age())
This approach can perform validation before an attribute is modified.
But calls need to use methods:
person.get_age()
person.set_age(25)
If a class has a large number of attributes, getters and setters will increase the number of interfaces and make the code look cumbersome.
2. Using property
property can wrap methods into an access interface similar to an ordinary attribute.
class Person:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise TypeError("年龄必须是整数")
if value < 0:
raise ValueError("年龄不能为负数")
self._age = value
Usage:
person = Person(20)
print(person.age)
person.age = 25
print(person.age)
Callers do not need to know that methods are used internally; they only need to operate as if accessing an ordinary attribute.
Attribute access process:
flowchart TD
A["External read or modification of age"] --> B{"Access type"}
B -->|"Read"| C["Call getter"]
B -->|"Assignment"| D["Call setter"]
C --> E["Return internal data"]
D --> F["Perform data validation"]
F --> G{"Validation passed?"}
G -->|"Pass"| H["Update internal attribute"]
G -->|"Fail"| I["Raise exception"]
E --> J["Complete access"]
H --> J
I --> K["Reject invalid modification"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,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:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3. Complete syntax of property
property is a Python built-in type and can be created with a decorator or constructor.
Decorator form:
class Product:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("价格不能为负数")
self._price = value
@price.deleter
def price(self):
del self._price
Constructor form:
class Product:
def __init__(self, price):
self._price = price
def get_price(self):
return self._price
def set_price(self, value):
if value < 0:
raise ValueError("价格不能为负数")
self._price = value
def delete_price(self):
del self._price
price = property(
get_price,
set_price,
delete_price,
"商品价格"
)
The parameters of property() are as follows:
| Parameter | Purpose |
|---|---|
fget |
Method called when getting the attribute |
fset |
Method called when setting the attribute |
fdel |
Method called when deleting the attribute |
doc |
Docstring of the attribute |
If no setter is provided, the property cannot be modified by assignment by default.
If no deleter is provided, the property cannot be deleted with del by default.
4. Read-only properties
Some properties can only be read and cannot be modified directly from outside.
For example, a user's registration time, order number, final product amount, etc.
from datetime import datetime
class User:
def __init__(self, username):
self.username = username
self._created_at = datetime.now()
@property
def created_at(self):
return self._created_at
Usage example:
user = User("Alice")
print(user.created_at)
user.created_at = datetime.now()
The assignment triggers an AttributeError because no setter is defined.
Note that a read-only property only restricts assignment through that attribute's interface; it does not mean the underlying data is absolutely unmodifiable. Outside code can still access _created_at, and the class itself can modify it too.
5. How property Works Under the Hood
The key to understanding property is understanding Python's descriptor protocol.
A descriptor is an object that implements certain special methods and can control how another object's attributes are read, assigned, and deleted.
Descriptors mainly involve three methods:
| Method | Purpose |
|---|---|
__get__() |
Called when reading the attribute |
__set__() |
Called when setting the attribute |
__delete__() |
Called when deleting the attribute |
property itself is a built-in descriptor type.
For example:
class Person:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
Here:
@property
def age(self):
return self._age
can be understood as:
age = property(age)
When you access:
person.age
Python's attribute lookup mechanism recognizes the property descriptor and calls its __get__() method.
When you execute:
person.age = 30
if a setter is defined, the corresponding __set__() method is called.
1. Types of Descriptors
Descriptors fall mainly into two categories:
Data descriptors
Descriptors that implement __set__() or __delete__().
Non-data descriptors
Descriptors that implement __get__() but not __set__() or __delete__().
The typical difference:
| Type | Methods Implemented | Can an Instance Attribute Override It? |
|---|---|---|
| Data descriptor | __set__ or __delete__ |
Usually not |
| Non-data descriptor | __get__ |
Yes |
| Regular instance attribute | No descriptor methods | It is itself an instance attribute |
2. Attribute Lookup Priority
For ordinary instance attribute access, Python's attribute lookup mechanism can be simplified as:
- Look for a data descriptor on the class and its inheritance chain.
- Look in the instance's own attribute dictionary.
- Look for a regular class attribute or non-data descriptor on the class and its inheritance chain.
- If still not found, consider fallback mechanisms such as
__getattr__().
This also involves __getattribute__(), which is the main entry point for instance attribute access.
Attribute lookup illustrated:
flowchart TD
A["访问 obj.name"] --> B["调用 __getattribute__"]
B --> C{"类中是否存在数据描述符"}
C -->|"是"| D["调用描述符 __get__"]
C -->|"否"| E{"实例属性字典是否存在 name"}
E -->|"是"| F["返回实例属性"]
E -->|"否"| G{"类中是否存在普通属性或非数据描述符"}
G -->|"是"| H["返回类属性或调用 __get__"]
G -->|"否"| I{"是否定义 __getattr__"}
I -->|"是"| J["调用 __getattr__"]
I -->|"否"| K["抛出 AttributeError"]
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:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This order is an important foundation for understanding the binding relationships among property, instance attributes, class attributes and methods.
Note that there are more specific rules for scenarios such as class attribute access, special attribute access, and custom __getattribute__(). The flow above is mainly for understanding ordinary instance attribute access.
3. Custom descriptors
Once you understand property, you can implement descriptors yourself.
For example, define a non-negative number descriptor:
class PositiveNumber:
def __set_name__(self, owner, name):
self.name = name
self.storage_name = f"_{name}"
def __get__(self, instance, owner):
if instance is None:
return self
return getattr(instance, self.storage_name)
def __set__(self, instance, value):
if not isinstance(value, (int, float)):
raise TypeError("必须是数字")
if value < 0:
raise ValueError("数值不能为负数")
setattr(instance, self.storage_name, value)
class Product:
price = PositiveNumber()
stock = PositiveNumber()
def __init__(self, price, stock):
self.price = price
self.stock = stock
Usage example:
product = Product(99.9, 100)
print(product.price)
print(product.stock)
product.price = 129.9
product.stock = -10
The last assignment raises a ValueError.
There are several important mechanisms here:
__set_name__()is called automatically when the descriptor is created as a class attribute, and is usually used to obtain the attribute name.__get__()controls attribute reading.__set__()controls attribute assignment.getattr()andsetattr()are used to access the data stored inside the instance.
Custom descriptors let you extract repeated attribute validation logic so it can be reused across multiple classes and multiple attributes.
4. The relationship between property and custom descriptors
Both are based on the descriptor protocol, but they apply to different scenarios.
| Comparison Aspect | property | Custom Descriptor |
|---|---|---|
| Implementation | Built-in descriptor | Custom class |
| Scope of Use | Usually used for a single attribute | Can be reused across multiple classes and attributes |
| Code Complexity | Relatively low | Relatively high |
| Validation Logic | Written in the getter and setter | Written in the descriptor class |
| Degree of Flexibility | Sufficient for controlling common attributes | Can implement more complex behavior |
In general:
- For simple attribute control within a single class, prefer
property. - If multiple classes need to reuse the same attribute management logic, consider a custom descriptor.
- Do not over-engineer just for the sake of using low-level mechanisms.