single and double underscore of class member name in Python
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
: 下划线开头的变量或方法只在内部使用,与Java不同,Python在“私有”和“公共”变量之间并没有很强的区别。var_
: 某个变量最合适的名称已被Python语言中的关键字占用,可以追加一个下划线来绕过命名冲突。__var
: 也称为名称改写(name mangling),双下划线前缀会让Python解释器重写属性名称,以避免子类中的命名冲突。__var__
: 双下划线方法通常被称为魔法方法,参考下表。_
: 循环中不需要访问运行的索引可以使用_
来表示临时值;还能表示REPL
会话中上一个表达式的结果。
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
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.me
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No privacy information is collected here