Encapsulation & Properties
Encapsulation hides internal data and provides controlled access through properties and methods. Python uses naming conventions (_private, __mangled) and @property decorator.
15 min•By Priygop Team•Updated 2026
Encapsulation
Encapsulation
class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius # "private" convention
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Below absolute zero!")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
self._celsius = (value - 32) * 5/9
# Usage
temp = Temperature(25)
print(f"{temp.celsius}°C = {temp.fahrenheit}°F")
temp.fahrenheit = 212
print(f"{temp.celsius}°C = {temp.fahrenheit}°F")
# temp.celsius = -300 # ValueError!
# Name mangling with double underscore
class Secret:
def __init__(self):
self.__hidden = "Can't access directly"
def reveal(self):
return self.__hidden
s = Secret()
print(s.reveal()) # Works
# print(s.__hidden) # AttributeError!
print(s._Secret__hidden) # Works (name mangling)Tip
Tip
Use @property for controlled attribute access. It lets you add validation without changing the API: obj.value = x calls the setter.
Diagram
Loading diagram…
Classes are syntactic sugar over prototypes.
Common Mistake
Warning
Python doesn't have truly private attributes. _ is convention (don't touch), __ uses name mangling but can still be accessed. It's about intent, not enforcement.
Practice Task
Note
(1) Create a Temperature class with @property for celsius/fahrenheit. (2) Add validation in the setter. (3) Test name mangling with __.