Encapsulation organizes related state and operations behind an intended way to use them. The caller of YearSpan.revise needs to know the accepted inputs and failure behavior, not every assignment inside the method. A standalone function can hide implementation details too; an object can additionally retain its own state between calls.
In Python, a leading underscore such as _start marks an internal detail by convention. It does not prevent reading or assigning it. A caller that assigns span._start directly can bypass validation, so our invariant is a promise of the supported operations, not a guarantee against arbitrary interference. Public attributes remain appropriate when direct changes need no special rule; an accessor for every field is not automatically better.
A double-leading underscore has a different mechanism, name mangling, which reduces accidental name collisions, particularly in subclasses:
class Exhibit:
def __init__(self, code):
self.__code = code
def code(self):
return self.__code
item = Exhibit("Q4")
print(item.code())
print(item._Exhibit__code)
try:
print(item.__code)
except AttributeError:
print("no attribute named __code")
Output:
Q4
Q4
no attribute named __code
Inside Exhibit, Python transforms __code into _Exhibit__code. The outside expression item.__code is not transformed in the same way. The mangled spelling is shown to explain the mechanism, not as a recommended interface. Special names such as __init__, with double trailing underscores, are not mangled.
Neither underscore convention is a security boundary or a way to keep secrets from someone with access to the running program. Authorization, secret storage, and other security needs require appropriate separate controls.