Search⌘ K
AI Features

Replacing Setters and Getters with a Python property

Explore how to replace traditional setters and getters in Python classes with property decorators to enable clean dot notation access for attributes. Understand the use of @property, @setter, and @deleter decorators to manage attribute behavior without breaking legacy code, making your Python classes easier to use and maintain.

We'll cover the following...

Let’s pretend that we have some legacy code that someone wrote who didn’t understand Python very well. If you’re like me, you’ve already seen this kind of code before:

Python
from decimal import Decimal
class Fees(object):
""""""
def __init__(self):
"""Constructor"""
self._fee = None
def get_fee(self):
"""
Return the current fee
"""
return self._fee
def set_fee(self, value):
"""
Set the fee
"""
if isinstance(value, str):
self._fee = Decimal(value)
elif isinstance(value, Decimal):
self._fee = value

To use this class, we have to use the setters and getters that are defined:

Python
f = Fees()
f.set_fee("1")
value = f.get_fee()
print(value)

If you want to add the normal dot notation access of attributes to this code without ...