Python Data Persistence – @Property DGCOrator

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


def adecorator(function): 
def wrapper():
return wrapper 
def decorate( ): 

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.


def name(self):
return self. ___myname
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.


def name(self,name):
self. ___myname=name
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 is as below:


#myclass. py
class MyClass:
__slots__=['__myname', '__myage']
def__init__(self, name=None, age=None):

def name(self) :
print ('name getter method')
return self.__myname

def age(self) :
print ('age getter method')
return self. ___myage

def name(self,name):
print ('name setter method')

def age(self, age):
print ('age setter method')

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.


>>> 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
name getter method
> > > obj1.about()
My name is Ashok and I am 30 years old