I am new to python language and 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)
CodePudding user response:
In Python, there is no existence of “private” instance variables that cannot be accessed except inside an object.
However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _xyz
should be treated as a non-public part of the API or any Python code, whether it is a function, a method, or a data member
CodePudding user response:
Here's why that's the "standard," a little different from other languages.
- No underscore indicates it's a public thing that users of that class can touch/modify/use
- 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.
- A truly private thing that you don't want anyone touching even those who know what they're doing, it's name mangled to include the classname like so
_Temp__c
. However, I would stay away from defaulting to two because it's not a great habit to make everything super-private unless needed as some sub-class might break it. 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 that's not enforced but rather accepted by the community to be private