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:

Setter Method:

Deleter Method:

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'

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.