Explain Codes LogoExplain Codes Logo

Does Python have “private” variables in classes?

python
encapsulation
best-practices
object-design
Alex KataevbyAlex Kataev·Dec 28, 2024
TLDR

In Python, we use a double underscore (__) prefix to indicate a variable should be treated like a private variable. This activates name mangling, obfuscating the variable from direct access outside the class, although it's still accessible if you know the secret handshake.

class MyClass: def __init__(self): self.__private_var = "Private" def reveal(self): return self.__private_var obj = MyClass() print(obj.reveal()) # No issue here: outputs "Private" print(obj._MyClass__private_var) # Not ideal, but it works: outputs "Private"

Access is achievable through _Classname__variable, but Python hopes you respect the __ hint not to peek behind the curtains.

Practical Encapsulation with Python

Python believes in consent over coercion. Instead of enforcing rigid accessor restrictions, Python promotes responsible behaviour with __ prefixes. It's like leaving your diary on the table but writing "Private" on the cover.

Better encapsulation can be achieved using @property decorators, which grant explicit control over attribute acess.

class MyClass: def __init__(self): self.__private_var = "Private" @property def privacy(self): """I'm like a bouncer for __private_var club.""" return self.__private_var @privacy.setter def privacy(self, value): raise AttributeError("No trespassing!")

This approach reveals data responsibly while frowning upon unjust modifications.

Name Mangling: Not a True Cloaking Device

The single underscore (_) prefix denotes non-public variables for internal use. Python's name mangling with __ prefix generates a class-specific variable name that's harder to stumble upon inadvertently.

  • Reduces mishaps: Accessing a mangled name without being aware feels like finding Waldo.
  • Debugger's ally: Keeps your internal variables out of the common namespace during debug sessions.
  • Safe for subclasses: Name clashes with attributes of subclasses are now rare Pokémon.

Python's Philosophy: Trust over Restrictions

If you miss high walls and moats around your variables, decorators and metaclasses are your fortresses in Python. Here, object design and security are castles built on a foundation of trust and transparency.

For deeper insights into these advanced concepts, Raymond Hettinger's writings are your tour guide to Python's circuitry and smart attribute management.

Encapsulation Approaches: Python Vs. Others

Languages like Java enforce strict access levels. Python, on the other hand, puts trust in the driver's seat, adopting a gentler, more flexible approach to variable visibility. It's like getting your own set of house keys instead of a curfew.

Python's approach fuels creativity, expects responsibility, and underlines the importance of mastering the tongue's conventions and best practices.