Background
In classic object-oriented programming, encapsulation is implemented through restricting access to internal data. Most languages have strict access modifiers. In Python, the principle is "we are all adults" — there is no strict privacy.
The Problem
Developers often confuse protected (_protected) and private (__private) attributes and methods in Python, believing that "double underscore" provides full protection, or thinking that there is no protection at all.
The Solution
Python implements conventions: a single underscore _var indicates protected, while double underscore __var indicates private (the name undergoes mangling). Access to such an attribute or method is possible, but harder: it is called _ClassName__var.
Example code:
class Example: def __init__(self): self._protected = 1 # protected self.__private = 2 # private (name mangling) ex = Example() print(ex._protected) # 1 #print(ex.__private) # AttributeError print(ex._Example__private) # 2 (name mangling)
Key features:
Is it possible to access a "private" field with a double underscore through an instance?
Yes, through mangling: _ClassName__var. So the data is accessible, just implicitly.
How will a private method/attribute behave during inheritance?
Name mangling prevents descendants from accidentally overriding the parent’s private elements, but access can be obtained through _ParentClass__attr. Methods with double underscores are not "visible" from outside the inheriting class.
class A: def __foo(self): print("A") class B(A): def bar(self): # self.__foo() — error self._A__foo() # works
Is there full privacy in Python like in JVM/C++?
No. Everything is based on conventions and mangling. Data cannot be fully protected, as Python dynamically allows access to any attributes.
In a large library, a user tried to change a private attribute using a double underscore, thinking it was a "secret" — but through _ClassName__var, the change still occurred.
Pros:
Cons:
In a project, it was agreed to use single underscores for internal fields and not to touch them outside the class. A property was added for safe access.
Pros:
Cons: