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))
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.
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.
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.
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.
The _
signals that these are private members. It's not enforced by the language in any way, since Python programmers are all "consenting adults".
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).
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