Type Here to Get Search Results !

Getter and Setters in Python with Example

0

 Getter and Setters in Python with Example


Getters and setters are methods used to access (get) and modify (set) the private attributes of a class. In Python, while we can directly access variables, we use getters and setters to control access, validate data, or trigger side effects.

When to Use Getters and Setters

  • You need to validate data before setting it.
  • You want to make a read-only property.
  • You plan to add logic when getting/setting (e.g., logging, triggering events).
  • You want to hide internal representation and provide a consistent interface.

Let's take basic example of Getters and Setters


class Person:
    def __init__(self, name, age):
        self.__name = name   # Private
        self.__age = age     # Private

    # Getter for name
    def get_name(self):
        return self.__name

    # Setter for name
    def set_name(self, new_name):
        if isinstance(new_name, str) and new_name:
            self.__name = new_name
        else:
            print("Invalid name")

    # Getter for age
    def get_age(self):
        return self.__age

    # Setter for age
    def set_age(self, new_age):
        if new_age >= 0:
            self.__age = new_age
        else:
            print("Age must be positive")

# Usage
p = Person("Alice", 25)
print(p.get_name())  # Alice
p.set_name("Bob")
print(p.get_name())  # Bob



Post a Comment

0 Comments