overview of property()
The property() function is used to define properties in the Python class. It is recommended to use the property decorator instead of the property() function.
use of property()
The property() function is used as shown below however, the recommended way is to use the property decorator.
#use of the property() function
class Dog():
def __init__(self, value):
self.hidden_name = value
# getter function
def get_name(self):
return self.hidden_name
# setter function
def set_name(self, value):
self.hidden_name = value
# deleter function
def del_name(self):
del self.hidden_name
# make a property
name = property(get_name, set_name, del_name)
rex = Dog('Rex')
print(rex.name)
The property() function is used to create a new class attribute called 'name' and define the three methods as properties.
When the new Dog is created, its name is set to 'Rex'. Finally, the name attribute is printed.
Rex
syntax of property()
The syntax of the property() function is:
property([fget=None, fset=None, fdel=None, doc=None])
arguments of property()
The property() function takes up to four arguments, all of them are optional.
argument |
required |
description |
fget |
optional |
function to get the attribute value, default value is None |
fset |
optional |
function to set the attribute value, default value is None |
fdel |
optional |
function to delete the attribute value, default value is None |
doc |
optional |
the docstring of the attribute, default value is None |
return value of property()
The property() function returns the property object.