Python Getter and Setter


Getters and Setters in Python OOP

Getters and setters are methods used in object-oriented programming to access and modify the private attributes of a class. They provide a controlled way to interact with the attributes of an object, allowing for encapsulation and data validation.

Key Points

  1. Encapsulation: Getters and setters help encapsulate the internal representation of an object. By using these methods, you can control how attributes are accessed and modified, which can help maintain the integrity of the data.

  2. Data Validation: Setters can include logic to validate data before it's set, ensuring that the object's state remains valid.

  3. Naming Conventions:

    • Getters usually start with the prefix get_, followed by the attribute name.
    • Setters usually start with the prefix set_, followed by the attribute name.

Example of Getters and Setters

Here’s a simple example to illustrate the use of getters and setters in Python:

class Person: def __init__(self, name, age): self.__name = name # Private attribute self.__age = age # Private attribute # Getter for name def get_name(self): return self.__name # Setter for name def set_name(self, name): self.__name = name # Getter for age def get_age(self): return self.__age # Setter for age with validation def set_age(self, age): if age < 0: raise ValueError("Age cannot be negative.") self.__age = age # Creating an instance of Person person = Person("Alice", 30) # Using getters print(person.get_name()) # Output: Alice print(person.get_age()) # Output: 30 # Using setters person.set_name("Bob") person.set_age(35) print(person.get_name()) # Output: Bob print(person.get_age()) # Output: 35 # Attempting to set an invalid age try: person.set_age(-5) # This will raise an exception except ValueError as e: print(e) # Output: Age cannot be negative.

Explanation of the Example

  1. Class Definition: The Person class has two private attributes: __name and __age.

  2. Getters:

    • get_name(): Returns the value of the private attribute __name.
    • get_age(): Returns the value of the private attribute __age.
  3. Setters:

    • set_name(name): Allows the name to be updated.
    • set_age(age): Updates the age only if the provided value is non-negative. If a negative age is attempted, it raises a ValueError.
  4. Creating an Instance: An instance of Person is created with the name "Alice" and age 30.

  5. Using Getters and Setters: The getters are used to retrieve the values, while the setters allow updating the attributes. An attempt to set an invalid age demonstrates the validation logic.

Summary

  • Getters and setters provide a way to control access to private attributes of a class, enhancing encapsulation and data integrity.
  • Setters can include validation logic to enforce rules on the data being set, preventing invalid states.
  • Although Python does not enforce strict encapsulation, using getters and setters is a common practice to manage access to class attributes.

If you have any specific questions or need further examples, feel free to ask!