Python property() With Examples

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

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()"Pankaj"


set_name called
get_name called
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 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"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
    def id(self):
        print('id getter')
        return self._id
    def id(self, i):
        print('id setter')
        self._id = i
    def id(self):
        print('id deleter')
        del self._id
d = Data() = 100


id setter
id getter
id deleter
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: