In Python, what is the underscore in front of the instance variable?
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 _
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).
It implies internal use only (similar to private in other languages), but is not restricted like other languages.
It's a convention stating that clients of the class/object should avoid using those attributes if possible as they are for internal use.
It just means the those attributes are for internal use only and if possible don't touch them.
Suppose You are editing some existing code and you see variables with underscore in front of them. it means that you should not edit them. Just a warning.
so
self.name = a
self._name =a
self.__name=a
are all same
精彩评论