Python Data Persistence – @Property DGCOrator
Although a detailed discussion on decorators is beyond the scope of this book, a brief introduction is necessary before we proceed to use @property decorator.
The function is often termed a callable object. A function is also a passable object. Just as we pass a built-in object viz. number, string, list, and so on. as an argument to a function, we can define a function that receives another function as an argument. Moreover, you can have a function defined in another function (nested function), and a function whose return value is a function itself. Because of all these features, a function is called a first-order object.
The decorator function receives a function argument. The behavior of the argument function is then extended by wrapping it in a nested function. Definition of function subjected to decoration is preceded by name of decorator prefixed with @ symbol.
Python-OOP – 113
Example
def adecorator(function): def wrapper(): function() return wrapper @adecorator def decorate( ): pass
We shall now use the property ( ) function as a decorator and define a name () method acting as a getter method for my name attribute in my class. py code above.
Example
@property def name(self): return self. ___myname @property def age(self): return self. __myage
A property object’s getter, setter, and deleter methods are also decorators. Overloaded name ( ) and age ( ) methods are decorated with name, setter, and age. setter decorators respectively.
Example
@name.setter def name(self,name): self. ___myname=name @age.setter def age(self, age): self. myage=age
When @property decorator is used, separate getter and setter methods defined previously are no longer needed. The complete code of myclass.py is as below:
Example
#myclass. py
class MyClass:
__slots__=['__myname', '__myage']
def__init__(self, name=None, age=None):
self.__myname=name
self.__myage=age
@property
def name(self) :
print ('name getter method')
return self.__myname
@property
def age(self) :
print ('age getter method')
return self. ___myage
@name.setter
def name(self,name):
print ('name setter method')
self.___myname=name
@age.setter
def age(self, age):
print ('age setter method')
self.__myage=age
def about(self):
print ('My name is { } and I am { } years old'.format(self. myname,self. myage))Just import above class and test the functionality of property objects using decorators.
Example
>>> from myclass import MyClass
>>> obj1=MyClass('Ashok', 21)
>>> obj1.about() #initial values of object's attributes
My name is Ashok and I, am 21 years old
>>> #change age property
>>> obj1.age=30
age setter method
>>> #access name property
>>> obj1.name
name getter method
'Ashok'
> > > obj1.about()
My name is Ashok and I am 30 years old