Python @property decorator tutorial
Why is it necessary to "install a door on the property"?
Exposing attributes directly in a class is like putting your house key outside the door - anyone can come in and change it at will, without any control at all.
This "streaking" design will allow illegal data (such as negative ages and oversized scores) to pollute your program at will, making it painful to troubleshoot.
The traditional solution is to use getter and setter methods to protect properties:
Safety is safety, but every time you read or write, you must writeobj.get_score()、obj.set_score(85), I always feel awkward - we are obviously operating an "attribute", but we are forced to use method calls, which is not Pythonic at all.
Python provides@propertyDecorators make methods look like ordinary properties, retaining encapsulation checks and keeping the call simple and elegant.
The core magic of @property
@propertyThe core purpose of: turn the "read" method into a property access, and turn the "write" method into an assignment operation.
Standard writing structure
Complete practice: student score classification
It’s completely natural to call
Did you see that? On the surface we are operatingscoreBehind this "attribute", a whole set of security verification is quietly running.
Create a read-only "calculated property"
If you only define @property without defining the corresponding setter, then this property becomes a read-only property - it cannot be assigned a value. It is especially suitable for values calculated in real time based on other attributes, such as age based on the year of birth and area based on width and height.
Example: The birth year can be changed, but the age is only readable
Test it
In this way, we can ensureagealways bybirthIt is accurately calculated and it is impossible for outsiders to tamper with the age value at will.
Some of the most common pitfalls for novices
1. The attribute name is the same as the internal variable name → infinite recursion
if you put@propertyIf the decorated method name is set to the same variable name as the internal variable name that actually stores data, a terrifying infinite loop will occur.
Correct practice: Use single underscore prefix for internal storage variables (such as_birth), this is a convention of the Python community, which means "this variable is for internal use and should not be touched by outsiders."
2. Forgot to initialize internal variables → report an error
use@propertyBefore, it must be__init__In the etc. method, put the corresponding internal variable (_xxx) is created, otherwise the attribute will not be found when accessing.
Practical example: screen resolution class
Combine readable and writable width and height with read-only resolution to write a practicalScreenkind.
Test effect
When to use it and when to boldly run naked
- Scenarios where @property is recommended
- Verification or conversion is required when assigning values (such as age ≥ 0, the string cannot be empty)
- Need to dynamically calculate read-only values (area, total price, age)
- Later in the project, I want to add control to the properties that were originally directly exposed, but I don’t want to change the external calling code.
- Scenarios where normal attributes can be used directly No additional logic is required, just storing and retrieving data. Python encourages "we are all trustworthy" and can be exposed directly, making the code simpler.
Summary
@propertyDecorators find the best balance between "naked" and "complicated": they allow you to operate ordinary properties and enjoy complete encapsulation protection. Learn it, and your Python class interface will become safe and elegant, and you will look like an experienced driver at first glance~

