This puzzle explores how Python handles “private” variables using name mangling, a mechanism that modifies variable names to avoid accidental access or override in subclasses.

Topics Covered

  • Name mangling
  • Private variables in classes
  • Attribute access and introspection

Puzzle Question

Why does direct access to __secret raise an error, and how can it still be accessed? What will the following code print?

Puzzle Code

class Spy:
    def __init__(self):
        self.__secret = "hidden"

    def reveal(self):
        return self.__secret

agent = Spy()

What will each of these lines do?

print(agent.reveal())
print(agent.__secret)
print(agent._Spy__secret)

Hints

  1. Double underscores at the start of a variable name trigger name mangling.
  2. Name mangling changes the variable name internally to avoid accidental access in subclasses.
  3. It’s still possible to access the variable — if you know the mangled name.

Answer

hidden
AttributeError
hidden

Explanation

  • agent.reveal() works because it accesses __secret from within the class where it was defined.
  • agent.__secret raises an AttributeError because the name has been mangled to _Spy__secret.
  • agent._Spy__secret works because it manually accesses the mangled name.

Learnings

  • Name Mangling: Python uses name mangling to help protect class internals from accidental overwrites or clashes, especially in subclasses.
  • Not Truly Private: Python doesn’t have true private variables — name mangling is only a convention-based safeguard.
  • Debugging & Introspection: Understanding name mangling is important when debugging, using dir(), or reflecting on class attributes.