w3resource

Python: property() function

property() function

The  property() function return a property attribute.

Version:

(Python 3.2.5)

Syntax:

property(fget=None, fset=None, fdel=None, doc=None)

Parameter:

Name Description Required /
Optional
fget function for getting the attribute value Optional
fset function for setting the attribute value Optional
fdel function for deleting the attribute value Optional
doc string that contains the documentation for the attribute. Optional

Example: Python property() function

class Example:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        print('Getting name')
        return self._name

    @name.setter
    def name(self, value):
        print('Setting name to ' + value)
        self._name = value

    @name.deleter
    def name(self):
        print('Deleting name')
        del self._name

x = Example('Bishop')
print('The name is:', x.name)

x.name = 'Anthony'

del x.name

Output:

Getting name
The name is: Bishop
Setting name to Anthony
Deleting name

Python Code Editor:

Previous: print()
Next: range()

Test your Python skills with w3resource's quiz



Python: Tips of the Day

How do I check if a list is empty?

For example, if passed the following:

a = []
if not a:
  print("List is empty")

Ref: https://bit.ly/2A4JXx9