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 = Nonedef get_name(self):print('get_name called')return self._namedef set_name(self, i):print('set_name called')self._name = idef del_name(self):print('del_name called')del self._namename = 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 calledget_name calledPankajdel_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@propertydef id(self):print('id getter')return self._id@id.setterdef id(self, i):print('id setter')self._id = i@id.deleterdef id(self):print('id deleter')del self._idd = Data()d.id = 100print(d.id)del d.id
Output:
id setterid getter100id deleter
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: Official Documentation
