This document provides a Python example demonstrating the use of getters and setters with the @property decorator to manage access to class attributes. It defines a 'Student' class with private attributes '_name' and '_age', along with corresponding getters and setters that include validation for setting values. The example illustrates how to use these properties and the importance of encapsulation in object-oriented programming.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
5 views2 pages
pycode
This document provides a Python example demonstrating the use of getters and setters with the @property decorator to manage access to class attributes. It defines a 'Student' class with private attributes '_name' and '_age', along with corresponding getters and setters that include validation for setting values. The example illustrates how to use these properties and the importance of encapsulation in object-oriented programming.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2
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