1.

Explain how and when Python’s built-in property() function should be used?

Answer»

Python doesn’t implement data encapsulation principle of object oriented programming methodology in the sense that there are no access restrictions like private, public or protected members. Hence a traditional method (as used in Java) of accessing instance variables using getter and setter methods is of no AVAIL in Python.

Python recommends use of property object to provide easy interface to instance attributes of a class. The built-in property() function uses getter , setter and deleter methods to return a property attribute corresponding to a specific instance variable.

Let us first write a STUDENT class with name as instance attributes. We shall provide getname() and setname() methods in the class as below:

class User:    DEF __init__(SELF, name='Test'):        self.__name=name    def getname(self):        return self.__name    def setname(self,name):        self.__name=name

We can declare its object and access its name attribute using the above methods.

>>> from example import User >>> a=User() >>> a.getname() 'Test' >>> a.setname('Ravi')

Rather than calling setter and getter function explicitly, the property object calls them whenever the instance variable underlying it is either retrieved or SET. The property() function uses the getter and setter methods to return the property object.

Let us add name as property object in the above User class by modifying it as follows:

class User:    def __init__(self, name='Test'):        self.__name=name    def getname(self):        print ('getname() called')        return self.__name    def setname(self,name):        print ('setname() called')        self.__name=name    name=property(getname, setname)

The name property, returned by property() function hides private instance variable __name.  You can use property object directly. Whenever, its value is retrieved, it is internally called getname() method. On the other hand when a value is assigned to name property, internally setname() method is called.

>>> from example import User >>> a=User() >>> a.name getname() called 'Test' >>> a.name='Ravi' setname() called

The property() function also can have deleter method. A docstring can also be specified in its definition.

property(getter, setter, deleter, docstring)

Python also has @property decorator that encapsulates property() function.



Discussion

No Comment Found