A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses. This is also called name mangling—the interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.
Enforced by the Python interpreter. Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).
The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.
Python automatically stores the value of the last expression in the interpreter to a particular variable called "_." You can also assign these value to another variable if you want.
I know what double underscore means for Python class attributes/methods, but does it mean something for method argument?
It looks like you cannot pass argument starting with double underscore to methods. It is confusing because you can do that for normal functions.
Consider this script:
def egg(__a=None):
return __a
print "egg(1) =",
print egg(1)
print
class Spam(object):
def egg(self, __a=None):
return __a
print "Spam().egg(__a=1) =",
print Spam().egg(__a=1)
Running this script yields:
egg(1) = 1
Spam().egg(__a=1) =
Traceback (most recent call last):
File "/....py", line 15, in <module>
print Spam().egg(__a=1)
TypeError: egg() got an unexpected keyword argument '__a'
I checked this with Python 2.7.2.
Some other examples
This works:
def egg(self, __a):
return __a
class Spam(object):
egg = egg
Spam().egg(__a=1)
This does not:
class Spam(object):
def _egg(self, __a=None):
return __a
def egg(self, a):
return self._egg(__a=a)
Spam().egg(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With