Getter and Setter Methods
Getter and Setter methods provide a controlled way to read (get) and update (set) an object's attribute values, rather than allowing them to be accessed or modified directly - especially useful for private attributes.
Basic Getters and Setters
class Account:
def __init__(self, balance):
self.__balance = balance # private attribute
def get_balance(self):
return self.__balance
def set_balance(self, amount):
if amount < 0:
print("Balance cannot be negative")
else:
self.__balance = amount
acc = Account(1000)
print(acc.get_balance()) # 1000
acc.set_balance(2000)
acc.set_balance(-500) # Balance cannot be negative
The setter method here adds validation logic, preventing the balance from ever being set to an invalid value - something direct attribute access wouldn't allow you to control.
A Cleaner Approach: the @property Decorator
Python's @property decorator lets you define getter and setter logic while still allowing the attribute to be accessed using simple, direct syntax rather than explicit method calls.
class Account:
def __init__(self, balance):
self.__balance = balance
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
if amount < 0:
print("Balance cannot be negative")
else:
self.__balance = amount
acc = Account(1000)
print(acc.balance) # 1000, reads like a plain attribute
acc.balance = 2000 # runs the setter logic behind the scenes
Coming Up Next
To close out this module, the final topic brings everything together with a complete Inheritance Case Study.
A Complete Property with Validation
Here is a full, runnable version of a validated property, plus a read-only one that is calculated on the fly:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance # goes through the setter below
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, amount):
if amount < 0:
raise ValueError("Balance cannot be negative")
self._balance = amount
@property
def is_premium(self): # read-only, no setter
return self._balance >= 100000
acc = Account("Asha", 5000)
acc.balance = 7500 # setter runs and validates
print(acc.balance) # 7500
print(acc.is_premium) # False
acc.is_premium = True # AttributeError: no setter defined
acc.balance = -10 # ValueError
Step by step, this is what Python does:
@propertyturnsbalanceinto a managed attribute on the class.- Reading
acc.balancesilently calls the getter method. - Assigning
acc.balance = 7500calls the setter, which checks the value before storing it in_balance. - Even
__init__uses the setter, so an invalid starting balance is rejected too. - A property with no setter, like
is_premium, cannot be assigned at all.
Single Versus Double Underscore
A single underscore, as in _balance, is a convention meaning "internal, please do not touch". Python does not stop anyone from using it. A double underscore, as in __balance, triggers name mangling: Python renames it internally to _Account__balance. This mainly prevents accidental clashes in subclasses; it is not real security, because the mangled name can still be accessed.
For most code, a single underscore behind a property is simpler and plays better with inheritance.
Where This Shows Up in Data Science Code
Properties are common in data tools you already use. A pandas DataFrame's shape and columns are attributes backed by logic, and scikit-learn estimators expose fitted results through attributes that only exist after training. In your own pipelines, properties are handy for:
- Validating hyperparameters, such as rejecting a learning rate of zero or a negative number of clusters.
- Computing derived values, like a model's accuracy from stored predictions, without storing them twice.
- Loading a large dataset lazily, only the first time the attribute is read.
Mistakes That Cause Confusing Bugs
| Mistake | What happens | Fix |
|---|---|---|
Setter assigns self.balance instead of self._balance | The setter calls itself forever: RecursionError | Store in a differently named attribute |
| Getter and setter names differ | The setter is attached to a different property | Use the same name in @property and @name.setter |
Writing Java-style get_x() for every field | Verbose code with no benefit | Start with plain attributes; add a property only when logic is needed |
| Slow work inside a getter | Simple attribute reads become expensive | Cache the result or use functools.cached_property |
A big advantage of properties is that you can switch from a plain attribute to a property later without changing any code that uses the class, because the access syntax stays the same.