Comment by nr378
4 days ago
You can hide fields in Python with a little bit of gymnastics:
class EncapsulatedCounter:
def __init__(self, initial_value):
_count = initial_value
def increment():
nonlocal _count
_count += 1
return _count
self.increment = increment
counter = EncapsulatedCounter(100)
new_value = counter.increment()
print(f"New value is: {new_value}")
Usually, a simple function is enough:
Example:
But it hides nothing:
"private" in Python is cultural, not enforced. (you can access `self.__private` from outside too if you want).