Learning Sections show
Getters and Setters in Python
Getters and setters in Python are used to ensure that an attribute's value is retrieved and updated in a controlled way. In Python, the @property decorator is used to define getters, setters, and deleters.
1. Using @property
The @property decorator allows you to define methods that behave like attributes. This makes the code more readable and maintainable.
Example:
class Person:
def __init__(self, name):
self._name = name
# Getter method
@property
def name(self):
return self._name
# Setter method
@name.setter
def name(self, value):
if isinstance(value, str) and value.strip():
self._name = value
else:
raise ValueError("Name must be a non-empty string")
# Create an instance of the class
person = Person("John")
# Access the name attribute using the getter
print(person.name) # Output: John
# Update the name attribute using the setter
person.name = "Jane"
print(person.name) # Output: Jane
# Attempt to set an invalid name
try:
person.name = ""
except ValueError as e:
print(e) # Output: Name must be a non-empty string
Getters and setters provide a way to control access to an attribute, allowing for validation and other logic to be applied when the attribute is accessed or modified.