Private variables and methods in Python

Possible duplicate:
Single and double underscore value in front of an object name in Python

Why should I use _foo (underscore) or __bar (double underscore) for private members and methods in Python?

+62
python private private-members
Aug 02 2018-10-10 at
source share
4 answers

Note that in Python there is no such thing as a "private method". Double underline is just the name:

>>> class A(object): ... def __foo(self): ... pass ... >>> a = A() >>> A.__dict__.keys() ['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__'] >>> a._A__foo() 

Thus, the __ prefix is ​​useful when you need manipulation to occur, for example, so that you don't encounter names up or down the inheritance chain. For other purposes, one underline would be better, IMHO.

EDIT, regarding the confusion on __ , PEP-8 is quite clear:

If your class is intended to be a subclass and you have attributes that you do not want to use subclasses, consider their double leading underscores and the absence of underscores. This calls the Python Name Rename Algorithm, where the class name is mutilated into the attribute name. This helps to avoid a collision attribute name should subclasses inadvertently contain attributes with the same name.

Note 3: Not everyone likes name manipulation. Try to balance the need to avoid accidental name conflicts with the potential use of advanced subscribers.

So, if you do not expect the subclass to accidentally override your own method with the same name, do not use it.

+64
Aug 02 '10 at 5:51
source share

Double underline. It manages the name in such a way that it cannot be accessed simply through __fieldName from outside the class you want to start with if they should be private. (Although it is still not very difficult to access the field.)

 class Foo: def __init__(self): self.__privateField = 4; print self.__privateField # yields 4 no problem foo = Foo() foo.__privateField # AttributeError: Foo instance has no attribute '__privateField' 

It will be available through _Foo__privateField . But he shouts, "I PRIVATE NOT TELL ME," which is better than nothing.

+33
Aug 2 2018-10-10 at
source share

Double underline. This changes the name. You can access the variable, but this is usually a bad idea.

Use single underscores for semi-private ones (tells python developers), just change this if you absolutely must ") and double for completely closed.

+9
Aug 02 '10 at 5:51
source share

Because it's a coding convention. See here for more details.

-3
Aug 2 '10 at 5:52
source share



All Articles