Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the double underscore __ mean in python? [duplicate]

Tags:

python

What does the double underscore indicate in python? I remember reading a tutorial that said it had something to do with a hidden variable, but I feel like there is more to it than that and I keep seeing examples of code that have double underscores and I don't understand what it means.

like image 625
david Avatar asked Oct 07 '13 04:10

david


People also ask

What does _ and __ mean in Python?

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”).

What is double __ in Python?

Double underscore before a nameThe leading double underscore tells the Python interpreter to rewrite the name in order to avoid conflict in a subclass. Interpreter changes variable name with class extension and that feature known as the Mangling.

What does the __ do in Python?

Single standalone underscore _ is a valid character for a Python identifier, so it can be used as a variable name. According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation. It is stored in the builtin module.

What is __ variable __ in Python?

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. But the data itself is still contained within the object.


1 Answers

From PEP 8:

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

like image 91
Mark Ransom Avatar answered Sep 28 '22 07:09

Mark Ransom