Search code examples
pythonclassencapsulation

single underscore vs double underscore encapsulation in python


I see that with help of underscore, one can declare private members in class but with one score, it is still accessed in main but with two it is not. If two makes the variable private then why there is single score one? What is the use/purpose of single underscore variable?

class Temp:
    def __init__(self):
    self.a = 123
    self._b = 123
    self.__c = 123

obj = Temp()
print(obj.a)
print(obj._b)
print(obj.__c)

Solution

  • Here's why that's the "standard," a little different from other languages.

    1. No underscore indicates it's a public thing that users of that class can touch/modify/use
    2. One underscore is more of an implementation detail that usually (note the term usually) should only be referenced/used in sub-classes or if you know what you're doing. The beautiful thing about python is that we're all adults here and if someone wants to access something for some really custom thing then they should be able to.
    3. Two underscores is name mangled to include the classname like so _Temp__c behind the scenes to prevent your variables clashing with a subclass. However, I would stay away from defaulting to two because it's not a great habit and is generally unnecessary. There are arguments and other posts about it that you can read up on like this

    Note: there is no difference to variables/methods that either have an underscore or not. It's just a convention for classes that's not enforced but rather accepted by the community to be private.
    Note #2: There is an exception described by Matthias for non-class methods