Tutorial Study Image

Python property()

The built-in function property() helps to define Python class properties. It gives an interface to instance attributes and provides property same as java and c#.


property(fget=None, fset=None, fdel=None, doc=None) #where all arguments are optional
 

property() Parameters:

Takes four optional parameters. If property() is called without any argument it returns a base property.

Parameter Description Required / Optional
fget  Function for getting the attribute value. Defaults to None. optional
fset  Function for setting the attribute value. Defaults to None. optional
fdel  Function for deleting the attribute value. Defaults to None. optional
doc  A string that contains the documentation (docstring) for the attribute. Defaults to None. optional

property() Return Value

If argument doc is not provided, property() takes the docstring of the getter function.

Input Return Value
 if argument property attribute

Examples of property() method in Python

Example 1: Create attribute with getter, setter, and deleter


class Person:
    def __init__(self, name):
        self._name = name

    def get_name(self):
        print('Getting name')
        return self._name

    def set_name(self, value):
        print('Setting name to ' + value)
        self._name = value

    def del_name(self):
        print('Deleting name')
        del self._name

    # Set property to use get_name, set_name
    # and del_name methods
    name = property(get_name, set_name, del_name, 'Name property')

p = Person('Adam')
print(p.name)
p.name = 'John'
del p.name
 

Output:

Getting name
The name is: Adam
Setting name to John
Deleting name

Note: Now, we set a new property attribute name by calling the property() method. As shown in the program, referencing p.name internally calls get_name() as a getter, set_name() as a setter, and del_name() as deleter through the printed output present inside the methods.

Example 2: Using @property decorator


class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        print('Getting name')
        return self._name

    @name.setter
    def name(self, value):
        print('Setting name to ' + value)
        self._name = value

    @name.deleter
    def name(self):
        print('Deleting name')
        del self._name

p = Person('Adam')
print('The name is:', p.name)
p.name = 'John'
del p.name
 

Output:

Getting name
The name is: Adam
Setting name to John
Deleting name