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.
Get hands-on with 1400+ tech skills courses.