Python property() function

Published February 16, 2022

In Python, the property() function returns an object of the property class, and it can be used to create a property of a class.   Property() returns an object of the property class as an argument, taking the delete, set, and get methods as arguments.

The Syntax of Property() method
The syntax of  the property() method  includes:

property(get(), set(), del(), doc())


where:
get()- gets  the attribute value
set()- sets  the attribute value
del()- deletes the attribute value
doc()- contains the documentation of the attribute


Example

class Person:
    def __init__(self, name):
        self._name = name
    def get_name(self):
        print('Get name')
        return self._name
    def set_name(self, value):
        print('Set name to ' + value)
        self._name = value
    def del_name(self):
        print('Deleting name')
        del self._name
    name = property(get_name, set_name, del_name, 'Name property')
p = Person('Calvin')
print(p.name)
p.name = 'Clein'
del p.name


Output

Get name
Calvin
Set name to Clein
Deleting name

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

303 Views