Methods and Functions

Python property()

Python property() function is used to create a property of the class. Property python function is mostly used in Python classes to define its properties by accepting the getter, setter, and deleter methods as arguments and returning an object of the property class.

In Python, there is a built-in function for declaring the properties of the program class, which is known as the property() function. Python property() built-in function and @property decorator is provided to easily implement the getters and setters methods in Object-Oriented Programming. So what exactly are getters and setters? Why are they used? Let us first understand what getters and setters are in brief.

Python getters and setters

The major reason getters and setters are used in object-oriented programming is to maintain data encapsulation. This is because we want to hide an object class’s attributes from other classes so that methods in other classes do not accidentally modify the data. Getters are methods that help you access private attributes or retrieve the value of private attributes, while setters help you update or set the value of private attributes.

property python

Python property()

The property() function is used in Python classes to define properties. In Python, Properties is a class for maintaining class attributes. Python property( ) is a built-in function for creating and returning a property object. In Python, the property() function offers an interface to instance attributes.

  • Syntax

                    

property(fget, fset, fdel, doc)

  • property() Parameters

The Python property() function accepts 4 optional parameters. They are:

fget (optional) = function for getting an attribute value. Default value is None

fset (optional) = function to set an attribute value. Default value is None

fdel (optional) = function used to delete an attribute value. Default value is None

doc (optional) = string that contains documentation (a docstring) for the attribute. Defaults to None

  • Return value from property()

It returns the property attributes from the specified getter, setter, and deleter.

Note –

  • If no arguments are provided, property() returns a base property attribute with no getter, setter, or deleter.
  • If the doc is not provided, property() uses the getter function’s docstring.

How Python property() works?

Consider a basic syntactical example where we create a new class attribute named ‘attr’ and define its 3 parameters as properties.

                    

attr = property(fget, fset, fdel)

Consider ‘x’ as an object instance of a class. Now when you refer to x.attr, Python then invokes the fget function.

Python calls the fset function and passes value as an argument when you assign x.attr = value.

When you run del x.attr Python invokes the fdel method.

Python uses the argument you parsed as doc as the attribute’s docstring.

Example 1: Create attribute with getter, setter, and deleter

Let us look at a simple program to understand how Python property() function works in real-life examples.

Example

                    

# Python program to illustrate property() function
class Person:
    def __init__(self, name):
        self._name = name

    # getter function
    def get_name(self):
        print('Getting name...')
        return self._name

    # setter function
    def set_name(self, value):
        print('Setting name to:', value)
        self._name = value

    # deleter function
    def del_name(self):
        print('Deleting name...')
        del self._name

    # Set property() to use get_name, set_name and del_name methods
    name = property(get_name, set_name, del_name)

p = Person('David')
print(p.name)
p.name = 'Rocky'
del p.name

Output

                    

Getting name...
David
Setting name to: Rocky
Deleting name...

In the above program, we have defined class Person. It has a single property attribute ‘name’. We have also declared 3 methods, they are get_name, set_name, and del_name.

  • get_name is used to retrieve the name of the Person,
  • set_name is used to set the name of the Person,
  • del_name is used to delete the name of the Person.

We then call the defined attribute ‘name’ by using the property() function.

Now, when we reference p.name, it internally calls the getter function get_name(). When we assign a new value to the name attribute, the property() function calls setter function – set_name() inside the Person class. And when we attempt to delete the name attribute, the del_name() method is invoked.

Example 2: Using python @property decorator

Python provides a feature that is called as Decorators that allows us to add functionality to the existing program. Decorators are used to changing how a function or class behaves. This is also known as Metaprogramming since a portion of the program attempts to modify another portion of the program during the compilation process. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function without affecting it permanently.

Instead of using Python property(), you can also assign the getter, setter, and deleter using the Python decorator @property. Using property as a decorator is a more elegant way to define properties in a class. The above program can be modified using the @property decorator as follows:

Example 1

                    

# Python program to illustrate @property decorator
class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        print('Getting name...')
        return self._name

    @name.setter
    def name(self, value):
        print('Setting name to:', value)
        self._name = value

    @name.deleter
    def name(self):
        print('Deleting name...')
        del self._name

p = Person('David')
print(p.name)
p.name = 'Rocky'
del p.name

Output

                    

Getting name...
David
Setting name to: Rocky
Deleting name...

We have used the @property decorator in this program instead of directly using the property() function. First, we specify the attribute name() method for the class Person. We do this by using the @property decorator before our getter function. We then use the same attribute name to define the setter and deleter. This can be seen as @name.setter and @name.deleter. When we use p.name now, it calls the necessary getter, setter, and deleter, as evidenced by the displayed output inside the method.

Note – We defined the getter, setter, and deleter using the same method name() but with distinct definitions.

Let us look at another example to understand @property decorator:

Example 2

                    

class Celsius:
    def __init__(self, temp):
        self._temp = temp

    @property
    def temp(self):
        print("Getting value...")
        return self._temp

    @temp.setter
    def temp(self, value):
        print("Setting value...")
        self._temp = value

c = Celsius(80)
print('Temperature in Celsius:', c.temp)
c.temp = 100

Output

                    

Getting value...
Temperature in Celsius: 80
Setting value...

Applications of property python

We may alter our class and implement the value constraint without requiring any changes to the client code by using the property() function in order for the implementation to be backward compatible.

Properties are typically utilized when additional processing (e.g., type checking or validation) is required when retrieving or setting an instance attribute.

The python property decorator is another approach for easily defining properties without manually executing the property() function. This is an additional significant function that allows the coder to include any other declared field into the code.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.