Course Content
In-Depth Python OOP
4. Polymorphism and Abstraction
In-Depth Python OOP
@property
@property
is a decorator that modifies the method inside a class to the class property.
To create the property, you should create a method with the @property
decorator above.
Code Description
CinemaHall
. The class has a constructor method __init__
that takes two parameters, rows
and seats_in_row
, which are used to initialize the instance attributes rows
and seats_in_row
.The interesting part is the
capacity
property, which is created using the @property
decorator. The capacity
property does not have a setter defined, which means it is a read-only property. This property calculates the capacity of the cinema hall based on the number of rows and seats in each row. When the capacity
property is accessed, the method defined below it (capacity
method) is automatically called, and its return value is used as the value of the property.The
capacity
method computes the capacity by multiplying the rows
and seats_in_row
attributes. When you access the capacity
property using hall.capacity
, it returns the calculated capacity of the cinema hall.In the usage part of the code, an instance of the
CinemaHall
class is created, named hall
, with 24 rows and 12 seats in each row. The capacity
property is accessed using hall.capacity
, and it returns the calculated capacity (24 * 12 = 288) and prints it.Next, the
rows
and seats_in_row
attributes of the hall
instance are updated to 5 and 11, respectively. When you access the capacity
property again using hall.capacity
, it recalculates the capacity (5 * 11 = 55) and prints the updated value.In summary, the
@property
decorator in Python allows you to define a read-only property for a class attribute. It lets you control how the attribute's value is retrieved without the need for explicit method calls, providing a clean and intuitive interface to access derived or computed attributes of the class.
In the example above, you can see a cinema hall that has attributes rows
and seats_in_row
. The capacity
property returns the total number of seats in the hall. It wouldn't make sense to create a separate attribute capacity
because if we change the number of rows
, we would have conflicting values. Specifically, no actions are performed with the class; only one of the hall's properties is returned.
Properties should have a specific logic: they should return a certain attribute of the class, unlike methods that are used to perform specific actions with the class.
How to define a new property?
Select the correct answer
Everything was clear?