Using Python's property() to Create Managed Attributes
This article explains the purpose, syntax, parameters, and return value of Python's property() function, demonstrates how to define getter, setter, and deleter methods both directly and via decorators, and provides additional examples and related built‑in attribute functions.
The property() function returns a managed attribute for new‑style classes, allowing controlled access to an object's data.
Syntax :
class property([fget[, fset[, fdel[, doc]]]])
Parameters :
fget – function that gets the attribute value
fset – function that sets the attribute value
fdel – function that deletes the attribute
doc – optional docstring for the attribute
The function returns a new‑style class property.
Example 1 – Explicit getter, setter, deleter :
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
c = C()
# c.x triggers getter, c.x = value triggers setter, del c.x triggers deleterIf a doc argument is supplied, it becomes the property's docstring; otherwise the docstring of fget is copied.
Example 2 – Using @property decorator for a read‑only attribute :
class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
# voltage() is now accessible as a read‑only attributeThe same decorator can be combined with .setter and .deleter to define writable properties:
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._xExample 3 – Custom class with property created via function call :
class ceshi():
def __init__(self, size=10):
self.size = size
def getSize(self):
return self.size
def setSize(self, value):
self.size = value
def delSize(self):
del self.size
x = property(getSize, setSize, delSize)
sx = ceshi(100)
print(sx.x) # getter
sx.x = 106 # setter
print(sx.x)
print(del sx.x) # deleter raises AttributeErrorAdditional built‑in functions for attribute manipulation include hasattr() , getattr() , setattr() , and delattr() , which respectively test for existence, retrieve, assign, and delete attributes on objects.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.