Python property decorator – Python @property

Filed Under: Python

Hello friends, today we will learn about Python property decorator. In our previous tutorial, we have discussed Python Decorator, you should read that if you are not familiar with the decorator before learning about python property decorator.

Python property decorator

As we discussed that we can decorate a function using decorators. There are some built-in decorators.

Python @property is one of the built-in decorators. The main purpose of any decorator is to change your class methods or attributes in such a way so that the user of your class no need to make any change in their code.

Consider the following class segment:


class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
        self.gotmarks = self.name + ' obtained ' + self.marks + ' marks'


st = Student("Jaki", "25")

print(st.name)
print(st.marks)
print(st.gotmarks)

It will output as below:


Jaki
25
Jaki obtained 25 marks

Now say we want to change the name attribute of the student class then what will happen? Append the following 3 line after the previous code:


st.name = "Anusha"
print(st.name)
print(st.gotmarks)

Then the output will be:
python property decorator

Notice that the name attribute got changed but the sentence that was created by the gotmarks attribute remained same as it was set during the initialization of the student object.

But we want gotmarks also to be changed when student name is updated. Here comes the use of python property decorator.

We can solve this problem with the following code.

Using Python Function to solve above problem


class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
        # self.gotmarks = self.name + ' obtained ' + self.marks + ' marks'

    def gotmarks(self):
        return self.name + ' obtained ' + self.marks + ' marks'


st = Student("Jaki", "25")
print(st.name)
print(st.marks)
print(st.gotmarks())

st.name = "Anusha"
print(st.name)
print(st.gotmarks())

It will output as follow:


Jaki
25
Jaki obtained 25 marks
Anusha
Anusha obtained 25 marks

Wow!!! Our requirement is solved. But have a close look at the code. We have removed the gotmarks attribute from the constructor and added a method named gotmarks.

So now in our class there is no attribute named gotmarks and we have a method named gotmarks().

And for this change, any user who is using my class will be in trouble as they have to replace all the attribute gotmarks with a function call gotmarks(). Assume there are 1000 lines of code then how troublesome it will be for the coder.

Solving above problem using Python property decorator

So we will solve this problem in pythonic way using the python property decorator. Notice the following code:


@property
def gotmarks(self):
   return self.name + ' obtained ' + self.marks + ' marks'

It will provide the same output as before, and don’t forget to remove the ‘()’ after gotmarks when printing it. Just writing @property above the function gotmarks() make it available to be used as a property.

And the user of our class doesn’t even know that attribute gotmarks is removed and we have a function for that. This is how the property decorator helps in keeping our code loosely coupled with the client code.

Python property setter

Now let’s say we want to set the name and marks attribute when we change the value of gotmarks. Deeply observe the code:


class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
        # self.gotmarks = self.name + ' obtained ' + self.marks + ' marks'

    @property
    def gotmarks(self):
        return self.name + ' obtained ' + self.marks + ' marks'

    @gotmarks.setter
    def gotmarks(self, sentence):
        name, rand, marks = sentence.split(' ')
        self.name = name
        self.marks = marks


st = Student("Jaki", "25")
print(st.name)
print(st.marks)
print(st.gotmarks)
print("##################")
st.name = "Anusha"
print(st.name)
print(st.gotmarks)
print("##################")
st.gotmarks = 'Golam obtained 36'
print(st.gotmarks)
print(st.name)
print(st.marks)

As we want to update the value of name and marks when we are setting the value of gotmarks. So using the setter of @proprety decorator we can achieve this.

Notice that we have written @gotmarks.setter that means we are applying the setter on the gotmarks method. And then we are splitting the sentence and updating the value of name and marks.

The above python property decorator with setter will produce below output.


Jaki
25
Jaki obtained 25 marks
##################
Anusha
Anusha obtained 25 marks
##################
Golam obtained 36 marks
Golam
36

That’s all about python property decorator and python @property setter examples.

Comments

  1. Carlos says:

    Thanks Pankaj for your explanation about @property, now I feel to be on the road.

  2. Nasir Haniffa says:

    Thank you for your simple explanation of decorators and @property.
    Now, I have got the clear picture (I guess).

    Do you have any tutorial for classmethods and static methods, please.

    1. Pankaj says:

      yes we have, use the search to get it easily and many other topics.

  3. deontics says:

    Notice that we have written @gotmarks.setter that means we are applying the setter on the gotmarks method. And then we are splitting the sentence and updating the value of name and marks.

    but if i do type(Student.gotmarks) it gives me , then howcome gotmarks got another attribute going by name of setter, which in turn can be used as decorator. This part needs more explanation.

  4. Surya Pr Singh says:

    @gotmarks.setter is not working as expected please check.

    1. Pankaj says:

      Can you please clarify what is not working. You can check the example output that it’s working as expected.

    2. Raviteja says:

      Surya Pr Singh it will help u

      class Student(): replace with class Student(object):

  5. PREETAM VERMA says:

    perfect and helpful

  6. hazem says:

    Can you explain in more depth

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages