Walls and a doorbell
Encapsulation
The analogy
You do not climb through a stranger's window to ask a question — you ring the doorbell. The house decides what to show you. Encapsulation means the messy insides are private, and the doorbell (a public method) is the only agreed way in.
Visualizer
Walls and a doorbell
step 1 / 7INSIDE THE WALLS — private
#wiring
#plumbing
#safeCode = "4821"
THE DOORBELL — public
ringBell()
requestEntry(name)
Private things behind the wall. Public things on the porch.
class House:
def __init__(self):
self.__safe_code = "4821" # name-mangled
def ring_bell(self): # public
return "who is it?"
h = House()
h.ring_bell() # fine
h.__safe_code # AttributeErrorCheck yourself
Why make a field private?