Python Getter and Setter Explained (With and Without @property)

Getter and setter methods are an essential part of Object-Oriented Programming (OOP) in Python. They help you control how class attributes are accessed and modified while following the principle of encapsulation.

In this article, you will learn Python getter and setter concepts step by step, including the modern and Pythonic way using the @property decorator.

What Are Getter and Setter Methods?

Getter and setter are methods that allow controlled access to class attributes. A getter retrieves the value, while a setter updates it after applying rules or validation.

Why Do We Use Getter and Setter?

  • Validation of input values
  • Read-only attributes
  • Better maintainability
  • Encapsulation of internal data

Getter and Setter Without @property

This is the traditional approach, commonly seen in languages like Java or C++.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_age(self):
        return f"Your age is {self.age}"

    def set_age(self, new_age):
        if 1 <= new_age <= 150:
            self.age = new_age
            return f"Age updated to {self.age}"
        else:
            return "Please enter a valid age"
    

Although this approach works, it is not considered Pythonic because users can still directly modify age without validation.

What Is the @property Decorator?

The @property decorator allows a method to behave like a normal attribute, while still giving you control over reading and writing values.

@property helps you enforce rules automatically without changing how the attribute is accessed.

Getter and Setter Using @property

class Student:
    def __init__(self, name, age):
        self.name = name
        self._age = age  # internal variable

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, new_age):
        if 1 <= new_age <= 150:
            self._age = new_age
        else:
            raise ValueError("Please enter a valid age")
    

Now, validation is enforced automatically whenever the attribute is accessed or modified.

Why Do We Use an Underscore (_) Variable?

The underscore variable stores the actual data, while the property controls access. Without this separation, Python may enter infinite recursion.

  • Prevents RecursionError
  • Prevents validation bypass
  • Makes code maintainable

What Happens Internally?

When you write:

s.age = 25
    

Python internally translates it to:

Student.age.fset(s, 25)
    

This ensures validation cannot be skipped.

Advantages and Disadvantages of @property

Advantage Explanation
Clean syntax Access attributes like variables
Encapsulation Hide internal implementation
API stability Logic can change safely

When Should You Use @property?

✔️ Use It When:

  • You need validation
  • You want read-only attributes
  • You want a clean public API

❌ Avoid It When:

  • Computation is expensive
  • Logic is too complex
  • A public attribute is sufficient

Real-Life Analogy

Without @property, a speed limit sign exists but can be ignored. With @property, a speed limiter is installed, and rules are enforced automatically.

Final Thoughts

While validation can be done without @property, using it ensures better encapsulation, cleaner syntax, and safer code. This is why @property is considered the Pythonic way to implement getters and setters.

Property controls access. Underscore variable stores data.

You May Also Like

About the Author: Nitesh

I am a software engineer and Enthusiastic to learn new things

Leave a Reply

Your email address will not be published. Required fields are marked *