Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære @property | Encapsulation
In-Depth Python OOP

@property

Sveip for å vise menyen

@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.

123456789101112131415
class CinemaHall: def __init__(self, rows, seats_in_row): self.rows = rows self.seats_in_row = seats_in_row @property def capacity(self): return self.rows * self.seats_in_row hall = CinemaHall(24, 12) print(hall.capacity) hall.rows = 5 hall.seats_in_row = 11 print(hall.capacity)

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.

question mark

How to define a new property?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 7

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

@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.

123456789101112131415
class CinemaHall: def __init__(self, rows, seats_in_row): self.rows = rows self.seats_in_row = seats_in_row @property def capacity(self): return self.rows * self.seats_in_row hall = CinemaHall(24, 12) print(hall.capacity) hall.rows = 5 hall.seats_in_row = 11 print(hall.capacity)

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.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 7
some-alt