Python property() function returns a property attribute. It’s mostly used to create a manageable class attribute.

Python property()

Python property() function syntax is:

  1. class property(fget=None, fset=None, fdel=None, doc=None)
  1. fget: function for getting the attribute value
  2. fset: function to set the attribute value
  3. fdel: function to delete the attribute
  4. 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.

  1. class Person:
  2. def __init__(self):
  3. self._name = None
  4. def get_name(self):
  5. print('get_name called')
  6. return self._name
  7. def set_name(self, i):
  8. print('set_name called')
  9. self._name = i
  10. def del_name(self):
  11. print('del_name called')
  12. del self._name
  13. name = property(get_name, set_name, del_name, "Person's Name Attribute")
  14. d = Person()
  15. d.name = 'Pankaj'
  16. print(d.name)
  17. del d.name

Output:

  1. set_name called
  2. get_name called
  3. Pankaj
  4. 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:

  1. 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:

  1. 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.

  1. class Data:
  2. def __init__(self):
  3. self._id = None
  4. @property
  5. def id(self):
  6. print('id getter')
  7. return self._id
  8. @id.setter
  9. def id(self, i):
  10. print('id setter')
  11. self._id = i
  12. @id.deleter
  13. def id(self):
  14. print('id deleter')
  15. del self._id
  16. d = Data()
  17. d.id = 100
  18. print(d.id)
  19. del d.id

Output:

  1. id setter
  2. id getter
  3. 100
  4. id deleter

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation