Property decorator ( @property ) : – In class generally we use parenthesis () to access any method. While using @property its allows us to access those methods without parenthesis ()
Example :-
class hello:
def print_hello(self):
return "Hello world !"
@property
def print_string(self):
return "This method is define with property decorator"
str1 = hello()
# calling the normal method with parenthesis
print(str1.print_hello())
# calling the property method without parenthesis its works same
print(str1.print_string)
Output:-
Hello world !
This method is define with property decorator
setter decorator ( @setter ) :- It is use to set the attribute at run time. it is allow to access to use attributes without setting getter and setter every where. This is also called ( mutator methods ) means a mutator method is a method used to control changes to a variable.
lets see an example or getter setter and deleter :- lets assume when a student change the name later but the email will not change without using @setter . So there is a problem , So to fix this problem we use @setter to set the attribute at run time.
class students:
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname
@property
def email(self):
return f"{self.fname}.{self.lname}@gmail.com"
@property
def fullname(self):
return f"{self.fname} {self.lname}"
# setter is use to change the attribute of objects at run time
@fullname.setter
def fullname(self,name):
self.fname, self.lname = name.split(' ')
# defining a deleter to delete the set attribute
@fullname.deleter
def fullname(self):
print("Name is deleted")
self.fname = None
self.lname = None
stud1 = students('web', "dev")
# here we changing the name of stud1 and setting a new name
stud1.fullname = "Mohammad Asif"
# deleting the attribute with del keyword
del stud1.fullname
print(stud1.fname)
print(stud1.lname)
print(stud1.email)
Output :-
Before setting new name
web
dev
web.dev@gmail.com
After setting new name. If you set name without using setter you will get an error.
Mohammad
Asif
Mohammad.Asif@gmail.com
After deleting the name
Name is deleted
None
None
None.None@gmail.com
I hope you understand the concept of getter, setter and property decorator. If you have any query or suggestion please do a comment.
Thank You!