Skip to content

single and double underscore of class member name in Python

homepage-banner

Single underscore

_single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose name starts with an underscore. However, nothing special is done with the name itself.

_foo: this is just a convention, a way for the programmer to indicate that the variable is private.

Double underscore

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

__foo: this has real meaning, the interpreter replaces this name with _classname__foo as a way to ensure that the name will not overlap with a similar name in another class.

__foo__: this is just a convention, a way for the Python system to use names that won’t conflict with user names.

Example

>>> class MyClass():
...     def __init__(self):
...         self.__superprivate = "Hello"
...         self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}

Summary

  • _var: Variables or methods starting with an underscore are used only internally. Unlike Java, Python does not have a strong distinction between “private” and “public” variables.
  • var_: If the most appropriate name for a variable is already occupied by a keyword in the Python language, you can append an underscore to bypass naming conflicts.
  • __var: Also known as name mangling, a double underscore prefix causes the Python interpreter to rewrite the attribute name to avoid naming conflicts in subclasses.
  • __var__: Double underscore methods are usually called magic methods, as shown in the table below.
  • _: In loops, _ can be used to represent a temporary value for a running index that does not need to be accessed. It can also represent the result of the previous expression in a REPL session.

Other magic methods in Python

Magic Method When it gets invoked (example) Explanation
__new__(cls [,...]) instance = MyClass(arg1, arg2) __new__ is called on instance creation
__init__(self [,...]) instance = MyClass(arg1, arg2) __init__ is called on instance creation
__cmp__(self, other) self == other, self > other, etc. Called for any comparison
__pos__(self) +self Unary plus sign
__neg__(self) -self Unary minus sign
__invert__(self) ~self Bitwise inversion
__index__(self) x[self] Conversion when object is used as index
__nonzero__(self) bool(self) Boolean value of the object
__getattr__(self, name) self.name # name doesn't exist Accessing nonexistent attribute
__setattr__(self, name, val) self.name = val Assigning to an attribute
__delattr__(self, name) del self.name Deleting an attribute
__getattribute__(self, name) self.name Accessing any attribute
__getitem__(self, key) self[key] Accessing an item using an index
__setitem__(self, key, val) self[key] = val Assigning to an item using an index
__delitem__(self, key) del self[key] Deleting an item using an index
__iter__(self) for x in self Iteration
__contains__(self, value) value in self, value not in self Membership tests using in
__call__(self [,...]) self(args) “Calling” an instance
__enter__(self) with self as x: with statement context managers
__exit__(self, exc, val, trace) with self as x: with statement context managers
__getstate__(self) pickle.dump(pkl_file, self) Pickling
__setstate__(self) data = pickle.load(pkl_file) Pickling

Reference

https://rszalski.github.io/magicmethods

Leave your message