Usage Of Property Decorator In Python¶
In this article we will learn about usage of property decorator in python. "property" is a built-in decorator in python. "property" is mostly used with classes. The decorator "property" makes the method that acts like an attribute to the python class. "property" is a callable object in python. It has three methods "getter", "setter" and "deleter".
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@property
def full_name(self):
return self.first_name + " " + self.last_name
@full_name.setter
def full_name(self, text):
self.first_name, self.last_name = text.split()
@full_name.deleter
def full_name(self):
del self.first_name
del self.last_name
# working with property "getter"
p = Person('Ram', 'B')
print(p.full_name)
# Output: Ram B
# working with property "setter"
p.full_name = "Arun B"
print(p.first_name)
# Output: Arun
print(p.last_name)
# Output: B
# working with property "deleter"
del p.full_name
print(p.full_name)
# Output: AttributeError: 'Person' object has no attribute 'first_name'
In above code we have created a Person object which first name "Ram" and last name "B". We have defined the method "full_name" which returns persons full name by combining the first name and last name of person object. We have used the property as decorator so, we can access the method as just like an attribute of a class. In above, when we use the code "p.full_name", It returned the full name as "Ram B". Property has three method getter, setter and deleter. By default property acts like getter. In python If we assign a value to a method then the method functionality will be lost. But, using a property we can set value. In above code, we set "Arun B" as value to property "full_name". When we set the value it is passed to the @fullname.setter
, there we process it. In above code we split it and updated the values of attributes "first_name" and "last_name". When we delete the property then the method @full_name.deleter
will be called. We can see the same in the above code "del p.full_name" when we execute it then it called @full_name.deleter
inside we have deleted attributes "first_name", "last_name". That's the reason we got an error "object has no attribute".