Python 3 reference · Built-in Functions
Python property() Function
Turn methods into a managed attribute with a getter, and optional setter and deleter. Usually written as @property.
Python 3 Since 3.0
Syntax
@property
def name(self): ...
@name.setter
def name(self, value): ...
Parameters
| Parameter | Description |
|---|---|
fget, fset, fdel optional |
Getter, setter and deleter functions. |
doc optional |
The docstring. |
Return value
A property descriptor.
Examples
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return round(3.14159 * self.radius ** 2, 2)
c = Circle(2)
print(c.area) # no parentheses: it reads like an attribute
Output
12.57
class Temperature:
def __init__(self):
self._celsius = 0
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
t = Temperature()
t.celsius = 21
print(t.celsius)
try:
t.celsius = -300
except ValueError as e:
print("ValueError:", e)
Output
21 ValueError: below absolute zero
Good to know
Start with plain attributes. Python lets you switch to a property later without changing the code that uses
the attribute, so there's no need for get_x() / set_x() methods.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
classmethod()· Turn a method into a class method that receives the class (cls) instead of an instance. Usually written as @classmethod.staticmethod()· Turn a method into a static method that receives neither the instance nor the class. Usually written as @staticmethod.getattr()· Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.setattr()· Set an attribute on an object by name, given as a string. setattr(obj, 'x', 5) is the same as obj.x = 5.- Python Classes and Objects · tutorial