What is Property Decorator in Python: Simple Explanation and Example
@property decorator in Python allows you to define methods that behave like attributes, letting you access method results using attribute syntax. It helps control access to instance data while keeping code clean and easy to read.How It Works
Imagine you have a box with a label on it. Normally, you open the box to get what's inside. But what if the label itself could tell you what's inside without opening the box? The @property decorator works like that label. It lets you use a method like a simple attribute, so you don't have to call it with parentheses.
Under the hood, when you use @property, Python treats the method as a special attribute. When you access it, Python runs the method and returns its result. This way, you can add logic to get or calculate values while keeping the syntax neat and simple.
Example
This example shows a class with a private attribute and a property to access it safely.
class Person: def __init__(self, first_name, last_name): self._first_name = first_name self._last_name = last_name @property def full_name(self): return f"{self._first_name} {self._last_name}" person = Person("Jane", "Doe") print(person.full_name)
When to Use
Use the @property decorator when you want to control how an attribute is accessed or calculated without changing how users of your class get the value. It is helpful when you want to:
- Calculate a value on the fly but access it like a simple attribute.
- Protect internal data by hiding the real attribute and exposing a controlled interface.
- Make your code cleaner and easier to read by avoiding explicit method calls.
For example, in a banking app, you might want to show the current balance calculated from transactions but prevent direct changes to the balance attribute.
Key Points
- @property turns a method into a readable attribute.
- It helps hide internal data and add logic when accessing values.
- Accessing a property looks like accessing a normal attribute, no parentheses needed.
- You can also define setter and deleter methods to control writing and deleting the property.