Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what is the underscore in front of the instance variable?

Tags:

python

oop

What convention is it?

class IndexedText(object):
    def __init__(self, stemmer, text):
        self._text = text
        self._stemmer = stemmer
        self._index = nltk.Index((self._stem(word), i) for (i, word) in enumerate(text))
like image 267
TIMEX Avatar asked Jul 14 '11 22:07

TIMEX


People also ask

What is the _ in front of variable Python?

The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8. This isn't enforced by Python.

What does _ and __ mean in Python?

The use of double underscore ( __ ) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses.

What is _ used for 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. Here is an example.

What is __ in Python called?

The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.


2 Answers

The _ signals that these are private members. It's not enforced by the language in any way, since Python programmers are all "consenting adults".

like image 114
Fred Foo Avatar answered Oct 04 '22 20:10

Fred Foo


According to PEP 8:

In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

It doesn't actually refer to the use of a single underscore in a member of a class, but these tend to be used to imply "internal use".

For a stronger version of the same thing, use two leading underscores (e.g. self.__foo). Python will make a stronger attempt to prevent subclasses from accidentally overwriting the member, but determined code can of course still do so.

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
like image 22
Daniel Pryden Avatar answered Oct 04 '22 22:10

Daniel Pryden