In-Depth Python OOP
In-Depth Python OOP
@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.
CinemaHall. The class has a constructor method
__init__that takes two parameters,
seats_in_row, which are used to initialize the instance attributes
The interesting part is the
capacityproperty, which is created using the
capacityproperty 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
capacityproperty is accessed, the method defined below it (
capacitymethod) is automatically called, and its return value is used as the value of the property.
capacitymethod computes the capacity by multiplying the
seats_in_rowattributes. When you access the
hall.capacity, it returns the calculated capacity of the cinema hall.
In the usage part of the code, an instance of the
CinemaHallclass is created, named
hall, with 24 rows and 12 seats in each row. The
capacityproperty is accessed using
hall.capacity, and it returns the calculated capacity (24 * 12 = 288) and prints it.
seats_in_rowattributes of the
hallinstance are updated to 5 and 11, respectively. When you access the
capacityproperty again using
hall.capacity, it recalculates the capacity (5 * 11 = 55) and prints the updated value.
In summary, the
@propertydecorator 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
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?