Encapsulation and Properties
Encapsulation restricts direct access to some of an object's components (data), preventing accidental modification, and forcing interaction through controlled methods (getters/setters).
Private Attributes (Convention)
Python does not enforce true privacy, but conventionally, attributes prefixed with an underscore (_) are considered protected/private, signaling that they shouldn't be accessed directly.
python class Student: def init(self, name, score): self.name = name self._score = score # Protected attribute
Using @property (Pythonic Getters)
The @property decorator allows you to define a method that can be accessed like an attribute. This enables calculated attributes and control over data access without changing the calling code.
python class Circle: def init(self, radius): self._radius = radius
# The getter method
@property
def radius(self):
return self._radius
# Calculated attribute accessed as if it were a stored variable
@property
def area(self):
return 3.14159 * (self._radius ** 2)
c = Circle(5)
Accessing area as an attribute, not a method:
print(f"Circle Area: {c.area}")