Python property()

shouryagautam's avatar
Published Sep 27, 2023

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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

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

All contributors

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours