The built-in function property() helps to define Python class properties. It gives an interface to instance attributes and provides property same as java and c#.
property(fget=None, fset=None, fdel=None, doc=None) #where all arguments are optional
Takes four optional parameters. If property() is called without any argument it returns a base property.
Parameter | Description | Required / Optional |
---|---|---|
fget | Function for getting the attribute value. Defaults to None. | optional |
fset | Function for setting the attribute value. Defaults to None. | optional |
fdel | Function for deleting the attribute value. Defaults to None. | optional |
doc | A string that contains the documentation (docstring) for the attribute. Defaults to None. | optional |
If argument doc is not provided, property() takes the docstring of the getter function.
Input | Return Value |
---|---|
if argument | property attribute |
class Person:
def __init__(self, name):
self._name = name
def get_name(self):
print('Getting name')
return self._name
def set_name(self, value):
print('Setting name to ' + value)
self._name = value
def del_name(self):
print('Deleting name')
del self._name
# Set property to use get_name, set_name
# and del_name methods
name = property(get_name, set_name, del_name, 'Name property')
p = Person('Adam')
print(p.name)
p.name = 'John'
del p.name
Output:
Getting name The name is: Adam Setting name to John Deleting name
Note: Now, we set a new property attribute name by calling the property() method. As shown in the program, referencing p.name internally calls get_name() as a getter, set_name() as a setter, and del_name() as deleter through the printed output present inside the methods.
class Person:
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
p = Person('Adam')
print('The name is:', p.name)
p.name = 'John'
del p.name
Output:
Getting name The name is: Adam Setting name to John Deleting name