property()

shouryagautam's avatar
Published Sep 27, 2023
Contribute to Docs

The property() function is a built-in Python function used to define methods that get, set, and delete class attributes. It can be used as a decorator or assigned to a class attribute.

Syntax

property(fget, fset, fdel, doc)

The property() function requires four parameters:

  • fget: function to get the value of the attribute.
  • fset: function to set the value of the attribute.
  • fdel: function to delete the value of the attribute.
  • doc: string that creates docstring for the attribute.

Note: If no arguments are given then the function returns a base property attribute without any getter, setter or deleter.

Example

The following example will demonstrate the use of property() function using the Pet class:

class Pet:
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
def set_name(self, name):
self._name = name
def del_name(self):
del self._name
name = property(get_name, set_name, del_name)
# Create an instance of Pet class
dog = Pet("Bruno")
# Access the name attribute using the property
print(dog.name)
# Set a new value for the name attribute
dog.name = "Mars"
# Access the updated name attribute
print(dog.name)
# Delete the name attribute
del dog.name

The code results in the following output:

Bruno
Mars

Codebyte Example

In this example the property() function is used to access the radius attribute of the Circle class.

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy