...

/

Properties—Getters and Setters

Properties—Getters and Setters

Learn what getters and setters are and how to use them.

Chirpy is growing rapidly—users, posts, likes, and comments are all coming together. However, as our platform expands, we start to encounter a new problem: unrestricted access to attributes.

Right now, attributes like display_name in User or content in Post can be accessed and modified freely from anywhere in the program.

This means:

  • A user’s display name could be set to an empty string or an unreasonably long name.

  • A post’s content could be set to thousands of characters, breaking formatting rules.

  • A user’s password could be accessed and printed—compromising security.

This lack of control can lead to inconsistent data, security risks, and unintended errors. We need a way to ensure that attributes are accessed and modified under specific rules.

To fix this, we need getters and setters. These are methods that control access to an attribute. Instead of directly modifying an attribute, we define methods that enforce rules and validation before making any changes.

In object-oriented programming, getters (or accessor methods) retrieve the value of a private attribute, while setters (or mutator methods) allow us to modify that value under controlled conditions. Python’s @property decorator makes it easy to define these methods so that attribute access appears as normal attribute retrieval or assignment, yet behind the scenes, validation or computation can take place.

Press + to interact

Let’s understand this with the help of a basic example:

Press + to interact
class Student:
def __init__(self):
# Private attribute
self._rollNo = None
# Setter
def set_roll_no(self, roll_no):
self._rollNo = roll_no
# Getter
def get_roll_no(self):
return self._rollNo
# Main execution
obj = Student()
obj.set_roll_no(123)
print(obj.get_roll_no())

In this example, we have a Student class with a private member variable rollNo ...