Here’s a simple Python example using getters (with @property) and setters
(@property.setter) to control access to class attributes:
✅ Basic Python Example Using Getters and Setters
class Student:
def __init__(self, name, age):
self._name = name # private attribute
self._age = age # private attribute
# Getter for name
@property
def name(self):
return self._name
# Setter for name
@name.setter
def name(self, new_name):
if len(new_name) > 0:
self._name = new_name
else:
print("Name cannot be empty.")
# Getter for age
@property
def age(self):
return self._age
# Setter for age
@age.setter
def age(self, new_age):
if new_age >= 0:
self._age = new_age
else:
print("Age must be positive.")
# Example usage
student = Student("Alice", 20)
print(student.name) # Calls getter: Alice
student.name = "Bob" # Calls setter
print(student.name) # Bob
student.age = -5 # Invalid age, setter prevents it
print(student.age) # Still 20
🔍 Key Notes:
_name and _age are protected (conventionally private).
@property lets you use obj.name like a regular attribute, but it actually
calls the getter.
You can control how values are read and changed (validation,
formatting, etc.).
Let me know if you want a version without decorators (manual getter