Today at work, I got to know about @property
decorator of Python and also @property.setter
.
It was quite cool to know and I want to leave a note about it.
@property
It is a built-int Python decorator that allows us to define property attributes of a class. Methods marked with @property
is also a getter method.
@property.setter
This decorator lets us set the value of a property of a class.
@property.deleter
This decorator lets us delete the assigned value by the setter method. The deleter is invoked with the help of a keyword del.
Example
class Student:
def __init__(self, name):
self._name = ''
@property
def name(self):
print("The value of the student name is: ")
return self._name
@name.setter
def name(self, val):
self._name = val
@name.deleter
def name(self):
del self._name
s = Student()
# Setting name
s.name = "Bob"
# Prints name
print(s.name)
# Deletes name
del s.name
# Name is deleted from above
# The below will throw an error
print(s.name)
While a method is called with parameters, a property is not.
With @property
, the syntax is unambiguous. The property is accessible with dot notation.