Encapsulation & Properties
Overview
Encapsulation is the practice of hiding an object's internal state to prevent external code from mutating it maliciously. Python is rebellious: it has no true private or protected keywords. Everything is technically public. Instead, Python relies on naming conventions: prefixing a variable with a single underscore _var indicates it's protected (for internal use only), while a double underscore __var triggers 'Name Mangling'. To provide safe read/write access, Python uses the @property decorator to create elegant getters and setters without requiring bulky get_X() syntax.
Syntax
class Employee:
def __init__(self, salary):
self.__salary = salary # Double underscore triggers Name Mangling
@property
def salary(self):
# The Getter (Access like a variable: emp.salary)
return self.__salary
@salary.setter
def salary(self, value):
# The Setter (Validates input before mutating)
if value < 0:
raise ValueError("Salary cannot be negative")
self.__salary = value
emp = Employee(50000)
emp.salary = 60000 # Triggers the setter cleanly
print(emp.salary) # Triggers the getterCommon Pitfalls
- Believing
__varis completely inaccessible. Python simply renames it under the hood to_ClassName__var. If a developer really wants to access it, they still can. Python assumes developers are consenting adults. - Writing Java-style
get_salary()andset_salary()methods. Using the@propertydecorator is vastly superior because it preserves clean dot-notation syntax.
Interview Questions
@property decorator preferred over public variables?If you start with a public variable obj.val and later realize you need to add validation before setting it, @property allows you to inject that logic without breaking existing code that accesses obj.val.
Real-World Example
Using properties to create computed, read-only attributes.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
# Computed instantly upon request; no setter is provided,
# making it effectively read-only.
return 3.14159 * (self.radius ** 2)Check Your Knowledge
Test your understanding of Encapsulation & Properties with these quick questions.