The @property Decorator in Python: Its Use Cases, Advantages, and Syntax (2023)

/ #Python
The @property Decorator in Python: Its Use Cases, Advantages, and Syntax (1)
Estefania Cassingena Navone
The @property Decorator in Python: Its Use Cases, Advantages, and Syntax (2)

🔹 Meet Properties

Welcome! In this article, you will learn how to work with the @property decorator in Python.

You will learn:

  • The advantages of working with properties in Python.
  • The basics of decorator functions: what they are and how they are related to @property.
  • How you can use @property to define getters, setters, and deleters.

1️⃣ Advantages of Properties in Python

Let's start with a little bit of context. Why would you use properties in Python?

Properties can be considered the "Pythonic" way of working with attributes because:

  • The syntax used to define properties is very concise and readable.
  • You can access instance attributes exactly as if they were public attributes while using the "magic" of intermediaries (getters and setters) to validate new values and to avoid accessing or modifying the data directly.
  • By using @property, you can "reuse" the name of a property to avoid creating new names for the getters, setters, and deleters.

These advantages make properties a really awesome tool to help you write more concise and readable code. ?

2️⃣ Intro to Decorators

A decorator function is basically a function that adds new functionality to a function that is passed as argument. Using a decorator function is like adding chocolate sprinkles to an ice cream ?. It lets us add new functionality to an existing function without modifying it.

In the example below, you can see what a typical decorator function looks like in Python:

def decorator(f): def new_function(): print("Extra Functionality") f() return new_function@decoratordef initial_function(): print("Initial Functionality")initial_function()

Let's analyze these elements in detail:

  • We first find the decorator function def decorator(f) (the sprinkles ✨) that takes a function f as an argument.
def decorator(f): def new_function(): print("Extra Functionality") f() return new_function
  • This decorator function has an nested function, new_function . Notice how f is called inside new_function to achieve the same functionality while adding new functionality before the function call (we could also add new functionality after the function call).
  • The decorator function itself returns the nested function new_function.
  • Then (below), we find the function that will be decorated (the ice cream ?) initial_function. Notice the very peculiar syntax (@decorator) above the function header.
@decoratordef initial_function(): print("Initial Functionality")initial_function()

If we run the code, we see this output:

Extra FunctionalityInitial Functionality

Notice how the decorator function runs even if we are only calling initial_function(). This is the magic of adding @decorator ?.

💡Note: In general, we would write @<decorator_function_name>, replacing the name of the decorator function after the @ symbol.

(Video) Python @property decorator explained

I know you may be asking: how is this related to the @property? The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

Now that you are familiar with decorators, let's see a real scenario of the use of @property!

🔸 Real-World Scenario: @property

Let's say that this class is part of your program. You are modeling a house with a House class (at the moment, the class only has a price instance attribute defined):

class House:def __init__(self, price):self.price = price

This instance attribute is public because its name doesn't have a leading underscore. Since the attribute is currently public, it is very likely that you and other developers in your team accessed and modified the attribute directly in other parts of the program using dot notation, like this:

# Access valueobj.price# Modify valueobj.price = 40000

💡 Tip: obj represents a variable that references an instance of House.

So far everything is working great, right? But let's say that you are asked to make this attribute protected (non-public) and validate the new value before assigning it. Specifically, you need to check if the value is a positive float. How would you do that? Let's see.

Changing your Code

At this point, if you decide to add getters and setters, you and your team will probably panic ?. This is because each line of code that accesses or modifies the value of the attribute will have to be modified to call the getter or setter, respectively. Otherwise, the code will break ⚠️.

# Changed from obj.priceobj.get_price()# Changed from obj.price = 40000obj.set_price(40000)

But... Properties come to the rescue! With @property, you and your team will not need to modify any of those lines because you will able to add getters and setters "behind the scenes" without affecting the syntax that you used to access or modify the attribute when it was public.

Awesome, right?

🔹 @property: Syntax and Logic

If you decide to use @property, your class will look like the example below:

class House:def __init__(self, price):self._price = price@propertydef price(self):return self._price@price.setterdef price(self, new_price):if new_price > 0 and isinstance(new_price, float):self._price = new_priceelse:print("Please enter a valid price")@price.deleterdef price(self):del self._price

Specifically, you can define three methods for a property:

  • A getter - to access the value of the attribute.
  • A setter - to set the value of the attribute.
  • A deleter - to delete the instance attribute.

Price is now "Protected"
Please note that the price attribute is now considered "protected" because we added a leading underscore to its name in self._price:

self._price = price

In Python, by convention, when you add a leading underscore to a name, you are telling other developers that it should not be accessed or modified directly outside of the class. It should only be accessed through intermediaries (getters and setters) if they are available.

🔸 Getter

Here we have the getter method:

(Video) Python OOP Tutorial 6: Property Decorators - Getters, Setters, and Deleters

@propertydef price(self):return self._price

Notice the syntax:

  • @property - Used to indicate that we are going to define a property. Notice how this immediately improves readability because we can clearly see the purpose of this method.
  • def price(self) - The header. Notice how the getter is named exactly like the property that we are defining: price. This is the name that we will use to access and modify the attribute outside of the class. The method only takes one formal parameter, self, which is a reference to the instance.
  • return self._price - This line is exactly what you would expect in a regular getter. The value of the protected attribute is returned.

Here is an example of the use of the getter method:

>>> house = House(50000.0) # Create instance>>> house.price # Access value50000.0

Notice how we access the price attribute as if it were a public attribute. We are not changing the syntax at all, but we are actually using the getter as an intermediary to avoid accessing the data directly.

🔹 Setter

Now we have the setter method:

@price.setterdef price(self, new_price):if new_price > 0 and isinstance(new_price, float):self._price = new_priceelse:print("Please enter a valid price")

Notice the syntax:

  • @price.setter - Used to indicate that this is the setter method for the price property. Notice that we are not using @property.setter, we are using @price.setter. The name of the property is included before .setter.
  • def price(self, new_price): - The header and the list of parameters. Notice how the name of the property is used as the name of the setter. We also have a second formal parameter (new_price), which is the new value that will be assigned to the price attribute (if it is valid).
  • Finally, we have the body of the setter where we validate the argument to check if it is a positive float and then, if the argument is valid, we update the value of the attribute. If the value is not valid, a descriptive message is printed. You can choose how to handle invalid values according the needs of your program.

This is an example of the use of the setter method with @property:

>>> house = House(50000.0) # Create instance>>> house.price = 45000.0 # Update value>>> house.price # Access value45000.0

Notice how we are not changing the syntax, but now we are using an intermediary (the setter) to validate the argument before assigning it. The new value (45000.0) is passed as an argument to the setter :

house.price = 45000.0

If we try to assign an invalid value, we see the descriptive message. We can also check that the value was not updated:

>>> house = House(50000.0)>>> house.price = -50Please enter a valid price>>> house.price50000.0

💡 Tip: This proves that the setter method is working as an intermediary. It is being called "behind the scenes" when we try to update the value, so the descriptive message is displayed when the value is not valid.

🔸 Deleter

Finally, we have the deleter method:

@price.deleterdef price(self):del self._price

Notice the syntax:

  • @price.deleter - Used to indicate that this is the deleter method for the price property. Notice that this line is very similar to @price.setter, but now we are defining the deleter method, so we write @price.deleter.
  • def price(self): - The header. This method only has one formal parameter defined, self.
  • del self._price - The body, where we delete the instance attribute.

💡 Tip: Notice that the name of the property is "reused" for all three methods.

This is an example of the use of the deleter method with @property:

# Create instance>>> house = House(50000.0)# The instance attribute exists>>> house.price50000.0# Delete the instance attribute>>> del house.price# The instance attribute doesn't exist>>> house.priceTraceback (most recent call last): File "<pyshell#35>", line 1, in <module> house.price File "<pyshell#20>", line 8, in price return self._priceAttributeError: 'House' object has no attribute '_price'

The instance attribute was deleted successfully ?. When we try to access it again, an error is thrown because the attribute doesn't exist anymore.

(Video) Python Tutorials - Property Decorators Part 1

🔹 Some final Tips

You don't necessarily have to define all three methods for every property. You can define read-only properties by only including a getter method. You could also choose to define a getter and setter without a deleter.

If you think that an attribute should only be set when the instance is created or that it should only be modified internally within the class, you can omit the setter.

You can choose which methods to include depending on the context that you are working with.

🔸 In Summary

  • You can define properties with the @property syntax, which is more compact and readable.
  • @property can be considered the "pythonic" way of defining getters, setters, and deleters.
  • By defining properties, you can change the internal implementation of a class without affecting the program, so you can add getters, setters, and deleters that act as intermediaries "behind the scenes" to avoid accessing or modifying the data directly.

I really hope you liked my article and found it helpful. To learn more about Properties and Object Oriented Programming in Python, check out my online course, which includes 6+ hours of video lectures, coding exercises, and mini projects.






(Video) the python @property decorator (beginner - intermediate) anthony explains #005





The @property Decorator in Python: Its Use Cases, Advantages, and Syntax (3)
Estefania Cassingena Navone

Developer, technical writer, and content creator @freeCodeCamp. I run the Español YouTube channel.

If you read this far, tweet to the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started


(Video) Python - Object Oriented Programming | Property Decorators


What is the advantage of @property in Python? ›

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

What are the advantages of using decorators in Python? ›

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

What is @property function in Python? ›

The @property Decorator

In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None) Here, fget is function to get value of the attribute. fset is function to set value of the attribute.

What does the Python decorator syntax '@' do? ›

The @register decorator simply stores a reference to the decorated function in the global PLUGINS dict. Note that you do not have to write an inner function or use @functools. wraps in this example because you are returning the original function unmodified.

What are 2 advantages of owning property? ›

10 Benefits of Owning a Home
  • You can control your monthly housing payment.
  • You'll build home equity with each monthly payment.
  • Your home value will rise over time.
  • You can use home equity to build wealth.
  • You can convert your home equity to cash.
  • You may get a tax deduction.
  • You'll build credit.
  • You can make the home your own.
Aug 30, 2022

What are decorators in Python with example? ›

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure.
Decorators have several use cases such as:
  • Authorization in Python frameworks such as Flask and Django.
  • Logging.
  • Measuring execution time.
  • Synchronization.

What are the advantages of decorators? ›

Advantage of Decorator Pattern

It enhances the extensibility of the object, because changes are made by coding new classes. It simplifies the coding by allowing you to develop a series of functionality from targeted classes instead of coding all of the behavior into the object.

What are the types of decorators in Python? ›

In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here. Before we get into the fun details of how a basic decorator works and how to implement your own decorators, let's see why we need them in the first place.

What is class decorator in Python? ›

What Is a Python Class Decorator? A Python class decorator adds a class to a function, and it can be achieved without modifying the source code. For example, a function can be decorated with a class that can accept arguments or with a class that can accept no arguments.

What are the key features and advantages of Python? ›

Python Features and Advantages
  • Easy to Code. Python is a very high-level programming language, yet it is effortless to learn. ...
  • Easy to Read. Python code looks like simple English words. ...
  • Free and Open-Source. ...
  • Robust Standard Library. ...
  • Interpreted. ...
  • Portable. ...
  • Object-Oriented and Procedure-Oriented. ...
  • Extensible.
Oct 28, 2022

How do you set attributes in Python? ›

Attributes of a class can also be accessed using the following built-in methods and functions :
  1. getattr() – This function is used to access the attribute of object.
  2. hasattr() – This function is used to check if an attribute exist or not.
  3. setattr() – This function is used to set an attribute.
Nov 23, 2020

What is the correct syntax for using a decorator? ›

Decorators use a special syntax in JavaScript, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.

What is decorator in Python with example interview questions? ›

When we mention the word "decorator", what enters your mind? Well, likely something that adds beauty to an existing object. An example is when we hang a picture frame to a wall to enhance the room. Decorators in Python add some feature or functionality to an existing function without altering it.

What pros and cons? ›

The pros and cons of something are its advantages and disadvantages, which you consider carefully so that you can make a sensible decision.

What are the 3 types of property? ›

In economics and political economy, there are three broad forms of property: private property, public property, and collective property (also called cooperative property).

How many types of decorators are there? ›

There are four types of decorators in Angular: Class Decorators. Property Decorators. Method Decorators.

What are the different types of decorators? ›

Class decorators, such as @Component and @NgModule. Property decorators for properties inside classes, such as @Input and @Output. Method decorators for methods inside classes, such as @HostListener. Parameter decorators for parameters inside class constructors, such as @Inject.

What is the role of a decorator? ›

Painters and decorators apply paint, wallpaper and other finishes to interior and exterior surfaces of buildings and other structures. They are employed by construction companies, painting contractors and building maintenance departments, or they may be self-employed.

What are the benefits of decorator design pattern? ›

Decorator design pattern allows us to dynamically add functionality and behavior to an object without affecting the behavior of other existing objects within the same class. We use inheritance to extend the behavior of the class.

What is the disadvantage of decorators? ›

Another disadvantage is the large number of decorator objects, for which a separate systematization is recommended to avoid similar overview problems when working with subclasses. Long call chains of the decorated objects (i.e. the extended software components) make it harder to spot errors and debug in general.

What are the uses of decoration? ›

The purpose of decoration is to make the space more aesthetically pleasing and functionally useful for the occupants, but this may include consideration of wider contextual issues such as fashion, culture, and so on.

Is @injectable a class decorator? ›

@Inject() and @Injectable

Statements that look like @SomeName are decorators. Decorators are a proposed extension to JavaScript. In short, decorators let programmers modify and/or tag methods, classes, properties and parameters. In this section the focus will be on decorators relevant to DI: @Inject and @Injectable .

How do you use a decorator in a class Python? ›

To decorate a method in a class, first use the '@' symbol followed by the name of the decorator function. A decorator is simply a function that takes a function as an argument and returns yet another function. Here, when we decorate, multiply_together with integer_check, the integer function gets called.

How do you make a decorator in Python? ›

Python provides two ways to decorate a class. Firstly, we can decorate the method inside a class; there are built-in decorators like @classmethod, @staticmethod and @property in Python. The @classmethod and @staticmethod define methods inside class that is not connected to any other instance of a class.

What is the basic syntax of Python? ›

The Python syntax defines a set of rules that are used to create Python statements while writing a Python Program. The Python Programming Language Syntax has many similarities to Perl, C, and Java Programming Languages. However, there are some definite differences between the languages.

What are two advantages of Python? ›

5 advantages of Python
  • Large developer community. Python is one of the most popular programming languages in the world. ...
  • Extensive libraries. Python offers a wide range of libraries that can be used across various applications. ...
  • Write less, do more. Python has very concise syntax. ...
  • Portability. ...
  • Wide range of use cases.

How do you get data from an object in Python? ›

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

What are the 3 attributes of Python? ›

Static methods, class methods, and instance methods all belong to the class. We can invoke the instance attributes using the class attribute by passing the instances of the object in the method. This feature saves the memory of the Python program.

How many types of attributes are there in Python? ›

There are two kinds of valid attribute names: data attributes and methods. The other kind of instance attribute reference is a method. A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well.

What is the importance of property? ›

Property rights provide the owner with the legal ownership of a resource. This is backed and enforced by the legal system as well as the protections government provides through law and order.

Why do we use properties? ›

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.

What are the uses of property? ›

Real property is the focal point of real estate, which deals with transactions (e.g., buying, selling, renting, and managing) involving land and buildings used for residential, commercial, and agricultural use. Just as there are various types of property, there are different types of interests in property.

What are the benefits of buying a property? ›

5 Real Benefits of Owning A Home
  • Building Equity. Your equity is the amount of the property you own. ...
  • Living Security. While renting, your situation is in the hands of the landlord, who may decide they no longer want to rent their property out. ...
  • Create Your Dream Home. ...
  • Control Over Costs. ...
  • Save Money.

What are the 3 main characteristic of property? ›

There are a few characteristics that help distinguish real property from other types of property.
  • It cannot be moved. ...
  • Location influences its value. ...
  • It has property rights attached to it.
Jun 17, 2021

What are the 4 ways to value a property? ›

What Are the Methods of Real Estate Valuation?
  • Sales Comparison Method. Also known as the market data approach, this method helps valuers analyse the current market rate of properties of a particular region to create a valuation report. ...
  • Profit Method. ...
  • Cost Method. ...
  • Residual Method. ...
  • Contractors Method. ...
  • Investment Method.
Jan 30, 2023


1. The Single Most Useful Decorator in Python
2. Python tricks: properties, staticmethods, and classmethods
(Sebastiaan Mathôt)
3. Python Decorators Made Easy
4. Python Tutorials - Property Decorators Part 2 | Properties
(Amulya's Academy)
5. Python Descriptors
6. Python's property() and Managing Attributes
(Real Python)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated: 02/16/2023

Views: 6222

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.