Lesson 27 / 49
Properties & Encapsulation
Control attribute access with underscore conventions and @property getters that add validation safely.
Naming conventions
Python has no true private keyword. A leading underscore _name signals "internal, don't touch" by convention only.
@property
@property turns a method into an attribute-like getter, so you can add validation without changing how callers use it.
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14159 * self._radius ** 2
c = Circle(4)
print(c.area) # 50.265... -- called like an attribute, no ()