DEV Community

Discussion on: Python/Django Developer Interview Questions and Answer (#1)

Collapse
chayimfriedman2 profile image
Chayim Friedman

Prefixing class variables does not make them "private"; all it does is prefixing them with the class name. So,

class MyClass:
    def __init__(self, a):
        self.__a = a

instance = MyClass(1)
# print(instance.__a) # AttributeError
print(instance._MyClass__a) # 1
Enter fullscreen mode Exit fullscreen mode
Collapse
manishanaidu profile image
Manisha Naidu Author • Edited on

There is no concept of private variables in Python. So "__" is just the convention followed to achieve similar concept.

Collapse
lhaze profile image
Łukasz Haze

"Name mangling" (so called) was't meant to be confused with the concept of "privacy". It's a common misconception. It's in the language to help to mitigate the problem of class field name collisions while the inheritance comes into the game. Think of the __slots__ class attribute or any API-like class mechanics using both inheritance and class fields (Django models). You may want to have each subclass add its value to the mechanics, not to override superclasses' values.

Collapse
chayimfriedman2 profile image
Chayim Friedman

Wait. Isn't it exactly what I said?

And besides, many developers (including me) prefers a single underscore, even though it has no meaning for Python.