Property Decorators
@property
is a built-in decorator in python language which is used to make functions
like getters, setters, deleter
in a class behave as class properties
.
Make a method behaves as attribute
/variable
General way - set, get & del using methods
class Vechicle:
def __init__(self, model):
self.__model = model
def get_model(self):
return self.__model
def set_model(self, model):
self.__model = model
def del_model(self):
del self.__model
if __name__ == '__main__':
v1 = Vechicle("Bolero")
print(v1.get_model())
v1.set_model('alto')
print(v1.get_model())
# v1.del_model()
Use @property
to - set, get del - as variable
class Pwskills:
def __init__(self, course_price):
self.__course_price = course_price
@property
def course_price(self):
return self.__course_price
@course_price.setter
def course_price(self, price):
self.__course_price = price
@course_price.deleter
def course_price(self):
del self.__course_price
if __name__ == '__main__':
pw = Pwskills(3500)
print(pw.course_price)
pw.course_price = 4300
print(pw.course_price)
# del pw.course_price_del
Using property()
method to - set, get del - as variable
class Alphabet:
def __init__(self, value):
self.__value = value
def get_value(self):
return self.__value
def set_value(self, value):
self.__value = value
def del_value(self):
print('Deleting value')
del self.__value
var_value = property(get_value, set_value, del_value)
if __name__ == '__main__':
x = Alphabet('GeeksforGeeks')
print(x.var_value)
x.var_value = 'GfG'
print(x.var_value)
# del x.var_value
Make email from firts + last name
class Employee8:
def __init__(self, first, last):
self.first = first
self.last = last
# if first or last is changes --> email will not get update
# self.email = '{}.{}@mail.com'.format(self.first.lower(),
# self.last.lower())
# Soln -- using @property
@property
def email(self):
return '{}.{}@mail.com'.format(self.first.lower(),
self.last.lower())
if __name__ == '__main__':
emp1 = Employee8('Amrit', 'Prasad')
emp2 = Employee8('Puja', 'kumari')
print(emp1.email)
print(emp2.email)
Capitalize name using @property
class Employee:
def __init__(self, f, l):
# calling setter
self.name = f + ' ' + l
@property
def name(self):
return self.first + ' ' + self.last
@name.setter
def name(self, var):
var1 = var.split()
self.first = var1[0].capitalize()
self.last = var1[1].capitalize()
if __name__ == '__main__':
e1 = Employee('amrit', 'Prasad')
print(e1.__dict__)
print(e1.first, e1.last)
print(e1.name)