Get, Set, and Delete Class Attributes in Python
In Python, getter, setter, and deleter methods are used to access, modify, and delete the attributes of a class in a controlled manner. This encapsulation helps maintain data integrity and provides an interface for managing the class attributes.
Getter Method:
- Definition: A getter method is used to retrieve the value of a private attribute.
- Purpose: It provides a way to access the value of a private member from outside the class.
- Usage: The getter method is usually prefixed with "get_" followed by the attribute name.
Setter Method:
- Definition: A setter method is used to set or update the value of a private attribute.
- Purpose: It provides a way to validate and modify the value before it is assigned to the attribute.
- Usage: The setter method is usually prefixed with "set_" followed by the attribute name.
Deleter Method:
- Definition: A deleter method is used to delete a private attribute from an object.
- Purpose: It provides a way to clean up resources or enforce rules before an attribute is removed.
- Usage: The deleter method is usually prefixed with "delete_" followed by the attribute name.
Example of Get, Set, and Delete Class Attributes
This example demonstrates the use of getter, setter, and deleter methods in a Python class.
Code Example
class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
self.__age = age # Private attribute
# Getter method for name
def get_name(self):
return self.__name
# Setter method for name
def set_name(self, name):
self.__name = name
# Getter method for age
def get_age(self):
return self.__age
# Setter method for age
def set_age(self, age):
if age >= 0: # Validation
self.__age = age
else:
print("Age cannot be negative.")
# Deleter method for name
def delete_name(self):
del self.__name
# Creating an object of the class
person = Person("Alice", 30)
# Using getter methods
print("Name:", person.get_name())
print("Age:", person.get_age())
# Using setter methods
person.set_name("Bob")
person.set_age(25)
print("Updated Name:", person.get_name())
print("Updated Age:", person.get_age())
# Using deleter method
person.delete_name()
# Attempting to access the deleted attribute
try:
print("Deleted Name:", person.get_name())
except AttributeError as e:
print(e)
Output
Name: Alice
Age: 30
Updated Name: Bob
Updated Age: 25
'Person' object has no attribute '_Person__name'
Age: 30
Updated Name: Bob
Updated Age: 25
'Person' object has no attribute '_Person__name'
Conclusion
Getter, setter, and deleter methods provide a controlled way to manage class attributes in Python. They enhance encapsulation and allow for validation and additional functionality when accessing and modifying the attributes.