Python property() function returns a property attribute. It’s mostly used to create a manageable class attribute.
Python property()
Python property() function syntax is:
class property(fget=None, fset=None, fdel=None, doc=None)
- fget: function for getting the attribute value
- fset: function to set the attribute value
- fdel: function to delete the attribute
- doc: creates the docstring for the attribute to be used in help() function.
Let’s look at an example to create property attribute in a class.
class Person:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
def set_name(self, i):
print('set_name called')
self._name = i
def del_name(self):
print('del_name called')
del self._name
name = property(get_name, set_name, del_name, "Person's Name Attribute")
d = Person()
d.name = 'Pankaj'
print(d.name)
del d.name
Output:
set_name called
get_name called
Pankaj
del_name called
Notice that Person name property is managed through specified methods and it’s using the _name
private property of Person.
We can create a read-only attribute or non-deletable attribute using property function.
If we define property function as:
name = property(get_name, set_name, None)
Then del d.name
will throw exception as AttributeError: can't delete attribute
.
Similarly, if we define property attribute as:
name = property(get_name, None, None)
The name will be read-only. If we try to set its value using d.name = 'Pankaj'
then exception will be thrown as AttributeError: can't set attribute
.
Python Property Decorator
We can use @property decorator to achieve the same thing.
class Data:
def __init__(self):
self._id = None
@property
def id(self):
print('id getter')
return self._id
@id.setter
def id(self, i):
print('id setter')
self._id = i
@id.deleter
def id(self):
print('id deleter')
del self._id
d = Data()
d.id = 100
print(d.id)
del d.id
Output:
id setter
id getter
100
id deleter
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: Official Documentation