In Python is nothing private/protected.
Quote:we're all consenting adults here
The are many tutorial about
_singel
and
__doble
underscore that are wrong,
because people compare it to C++/Java.
Can take a little about it.
_singel
underscore tells user that this is internal attribute,can be changed but best to leave alone.
__doble
underscore causes the name to be mangled to something else.
What's important with
__doble
is that attributes cannot be overridden via inheritance(because of
name mangling
).
Eg:
class A:
_info = 'Do not change' # Internal class attribute
def __init__(self):
self.__key = 99 # private copy of this key
def __foo(self):
print('hello')
class B(A):
def __init__(self):
super().__init__()
# Does not override A.__key
self.__key = 100
# Does not override A.__foo_method()
def __foo(self):
print('world')
Use it,now we see how name mangling work with inheritance.
>>> obj = B()
>>> obj._A__key
99
>>> obj._B__key
100
so
self.__key
has same name in A and B,
but get
name mangling
to different names for each class.
The same with method:
>>> obj._A__foo()
hello
>>> obj._B__foo()
world
>>> # Class variable/attribute is shared with all classes
>>> obj._info
'Do not change'