Course contentsShow
← Python
Lesson 468 of 1,0607. Object-Oriented ProgrammingFree lesson

Encapsulating Attribute Access with Properties

Use the @property decorator to define getter methods that allow controlled access to internal object state.

In this lesson, you will learn how to use the @property decorator to create "getter" methods that allow you to control and calculate how attributes are accessed.

Why Use Properties?

In object-oriented programming, it is often best practice to keep internal data private. However, sometimes you want an object to provide an attribute that isn't stored directly, but is instead calculated on the fly.

Usually, if you want to perform logic when someone accesses an attribute, you might write a method like get_price(). However, calling my_obj.get_price() feels different than accessing a simple attribute like my_obj.price. The @property decorator allows you to define a method that behaves exactly like an attribute, providing a cleaner, more intuitive interface.

Defining a Property

Imagine a Product class where the price includes tax. Instead of updating the price manually, we can define a property that calculates it whenever we ask for it:

class Product:
    def __init__(self, base_price):
        self._base_price = base_price  # The underscore indicates internal state

    @property
    def price_with_tax(self):
        # This method is now accessed as an attribute
        return self._base_price * 1.10

item = Product(100)
print(item.price_with_tax)  # Notice: no parentheses needed!

How It Works

When you decorate a method with @property, Python treats that method as a read-only attribute. When you reference item.price_with_tax in your code, Python automatically executes the function and returns the calculated value.

This approach is powerful because it hides the complexity of your calculations. If the tax rate changes or the logic becomes more complex later, you can update the code inside the property method without changing how the rest of your program interacts with the Product object. You maintain complete control over the internal state while presenting a simple, attribute-like interface to the outside world.

Key Takeaway: The @property decorator allows you to define methods that are accessed like attributes, enabling you to add logic to data access while keeping your class interface clean and consistent.