Python property()
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 createsdocstringfor 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 = namedef get_name(self):return self._namedef set_name(self, name):self._name = namedef del_name(self):del self._namename = property(get_name, set_name, del_name)# Create an instance of Pet classdog = Pet("Bruno")# Access the name attribute using the propertyprint(dog.name)# Set a new value for the name attributedog.name = "Mars"# Access the updated name attributeprint(dog.name)# Delete the name attributedel dog.name
The code results in the following output:
BrunoMars
Codebyte Example
In this example the property() function is used to access the radius attribute of the Circle class.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
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