Getter and Setter in Python

In Python, getters and setters are methods used to control access to an object's attributes. They provide a way to implement data encapsulation, ensuring that attributes are accessed and modified in a controlled manner.

Getters retrieve the value of an attribute, while setters allow you to modify it. This approach helps prevent direct manipulation of attributes from outside the class.

Basic Class with Public Attributes

Let's start with a simple class that has a public attribute ?

class YearGraduated:
    def __init__(self, year=0):
        self.year = year

# Create an instance
student = YearGraduated(2020)
print(student.year)

# Direct access (not recommended for sensitive data)
student.year = 2021
print(student.year)
2020
2021

Using Getter and Setter Methods

Now let's implement proper getter and setter methods to control attribute access ?

class YearGraduated:
    def __init__(self, year=0):
        self._year = year  # Protected attribute

    # Getter method
    def get_year(self):
        return self._year

    # Setter method
    def set_year(self, year):
        if year > 1900 and year <= 2024:
            self._year = year
        else:
            print("Invalid year! Must be between 1900 and 2024")

# Create instance and use getter/setter
student = YearGraduated()
print(student.get_year())

# Set valid year
student.set_year(2019)
print(student.get_year())

# Try to set invalid year
student.set_year(1800)
0
2019
Invalid year! Must be between 1900 and 2024

Using the @property Decorator

Python provides a more elegant way to implement getters and setters using the @property decorator ?

class YearGraduated:
    def __init__(self, year=0):
        self._year = year

    @property
    def year(self):
        """Getter method"""
        return self._year

    @year.setter
    def year(self, value):
        """Setter method with validation"""
        if value > 1900 and value <= 2024:
            self._year = value
        else:
            raise ValueError("Year must be between 1900 and 2024")

# Usage - looks like direct attribute access
student = YearGraduated()
print(student.year)

student.year = 2022
print(student.year)

# This will raise an error
try:
    student.year = 1800
except ValueError as e:
    print(f"Error: {e}")
0
2022
Error: Year must be between 1900 and 2024

Private Attributes with Double Underscore

Python uses name mangling for attributes with double underscores, making them harder to access from outside the class ?

class YearGraduated:
    def __init__(self, year=2000):
        self.__year = year  # Private attribute

    @property
    def year(self):
        return self.__year

    @year.setter
    def year(self, value):
        if isinstance(value, int) and 1900 < value <= 2024:
            self.__year = value
        else:
            raise ValueError("Invalid year")

student = YearGraduated()
print(student.year)

student.year = 2023
print(student.year)

# Direct access to private attribute will fail
try:
    print(student.__year)
except AttributeError as e:
    print("Cannot access private attribute directly")
2000
2023
Cannot access private attribute directly

Comparison of Approaches

Approach Syntax Best For
Direct Access obj.attr Simple cases without validation
Getter/Setter Methods obj.get_attr() Explicit control, Java-like approach
@property Decorator obj.attr Pythonic, clean syntax with validation

Conclusion

The @property decorator provides the most Pythonic way to implement getters and setters. It allows you to add validation and logic while maintaining clean attribute-like syntax. Use getters and setters when you need to control access to your class attributes.

Updated on: 2026-03-15T17:19:35+05:30

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements