Create managed attributes with the property() built-in function.
What You Will Learn
property(fget, fset=None, fdel=None, doc=None) builds a descriptor. Decorator syntax is usually more readable, but property() is useful for defining getters and setters programmatically.
The @property decorator is idiomatic for straightforward class definitions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class Rectangle:
def __init__(self, width):
self._width = width
def get_width(self):
return self._width
def set_width(self, value):
if value <= 0:
raise ValueError("Width must be positive")
self._width = value
width = property(get_width, set_width)
rectangle = Rectangle(5)
rectangle.width = 8
print(rectangle.width)
How the Example Works
- The class Rectangle groups data and behavior; its methods run when called on an instance.
- The variable rectangle holds the result of Rectangle(5). Later lines use that value or inspect how it changes.
- The variable rectangle.width holds the result of 8. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression rectangle.width prints 8. Compare that result with the rule above before you change the argument.
Expected output from the example:
8
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Define a read-only calculated area property with property().
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assigning to a read-only property without providing a setter.
- Calling a managed property from its own setter and causing recursion.
Key Takeaways
- Create managed attributes with the property() built-in function.
- property(fget, fset=None, fdel=None, doc=None) builds a descriptor.
- The @property decorator is idiomatic for straightforward class definitions.