How to Use Getter and Setter in Python: Simple Guide
In Python, use the
@property decorator to create a getter method and @.setter to create a setter method. This allows controlled access to private attributes while using simple attribute syntax.Syntax
Use @property above a method to make it a getter. Use @property_name.setter above another method to make it a setter for the same attribute.
This lets you access and set the attribute like a normal variable but with extra control.
python
class MyClass: def __init__(self, value): self._value = value # private attribute @property def value(self): return self._value @value.setter def value(self, new_value): self._value = new_value
Example
This example shows how to use getter and setter to control access to a private attribute _age. The setter checks that the age is not negative.
python
class Person: def __init__(self, age): self._age = age @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("Age cannot be negative") self._age = value p = Person(25) print(p.age) # prints 25 p.age = 30 print(p.age) # prints 30 try: p.age = -5 except ValueError as e: print(e)
Output
25
30
Age cannot be negative
Common Pitfalls
One common mistake is forgetting to use the @property decorator, which means the method won't act like an attribute.
Another is not using a private attribute (like _value) inside the getter and setter, causing infinite recursion.
python
class Wrong: def __init__(self, value): self.value = value def value(self): # Missing @property return self.value # Causes infinite recursion class Right: def __init__(self, value): self._value = value @property def value(self): return self._value @value.setter def value(self, new_value): self._value = new_value
Quick Reference
- @property: Makes a method act like a getter.
- @property_name.setter: Defines the setter for the property.
- Use a private attribute (like
_attr) to store the actual value. - Access the property like a normal attribute (no parentheses).
Key Takeaways
Use @property to create a getter method that looks like an attribute.
Use @property_name.setter to create a setter method for controlled attribute assignment.
Always store the real value in a private attribute to avoid recursion.
Access properties like normal attributes without parentheses.
Setters can include validation or extra logic before assigning values.