Python lessons – 7.7 Properties

Python lessons - 7.7 properties

Properties

The properties provide a way to customize access to the attributes of the instance. To create them, you use the @property decorator put before the method. Their purpose is to define read-only attributes (they can not be modified).

class Pizza:
    def __init__(self, toppings):
        self.toppings = toppings
    
    @property
    def pineapple_allowed(self):
         return False

pizza = Pizza(["cheese","tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True 

Properties can also be set to define getter/setter functions. The setter function sets the value of the corresponding property. The getter function obtains its value

To define a setter, you need to use a decorator with the same name as the property, followed by a dot and the setter clause. The same rule applies to getter.

⇐Go to Python Lesson 7.6 – Class methods and static methods

End of Python course

Leave a Reply