Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
object oriented
class
property decorator

What is the @property in Python?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The @property is a decorator. In Python, decorators enable users to use the class in the same way(irrespective of the changes made to its attributes or methods). The @property decorator allows a function to be accessed like an attribute.

Example

Suppose there is a class called Greet (shown below):

class Greet:
def __init__(self, country, greeting):
self.country = country
self.greeting = greeting
self.greet = Greeting + " from " + Country

And a user makes use of this class in the following manner:

Obj = Greet("France", "Bonjour")
print(Obj.greet)

A change in the implementation of the class Greet

Upon realizing that, ​when the user only updates greeting or country, the variable greet is not updated; the creator of the class decides to make a function out of it. The class now looks something like this:

class Greet:
def __init__(self, country, greeting):
self.country = country
self.greeting = greeting
def greet(self):
return self.greeting + " from " + self.country

Usage of the @property

The user will now have to replace Obj.greet with Obj.greet() everywhere in the code. This is clearly undesirable so, ​to prevent this, we use the@property:

class Greet:
def __init__(self, country, greeting):
self.country = country
self.greeting = greeting
@property
def greet(self):
return self.greeting + " from " + self.country

The user can use now use the function greet() just like she used the attribute greet:

Obj = Greet("France", "Bonjour")
print(Obj.greet)

RELATED TAGS

python
object oriented
class
property decorator
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring