例如,如果我创建一个点类。
课点:
def__init__(self, x, y):
self._x = x
self._y = y
和
课点:
def__init__(self, x, y):
self.x = x
self.y = y
self._x 和 just self.x 的使用有什么区别。
最佳答案
单下划线只是一种命名约定,表示该属性应被视为“半私有(private)”(类似地,双下划线表示“私有(private)”),但它没有语义差异:代码的两个版本都应该行为完全一样。根据PEP-8 :
_single_leading_underscore
: weak "internal use" indicator. E.g.from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts with a Python keyword.
__double_leading_underscore
: when naming a class attribute, invokes name mangling (inside classFooBar
,__boo
becomes _FooBar__boo
).
__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.
如果出于某种原因,您有一个以下划线为前缀的变量,并且可以公开访问该变量,那么最好在模块的 __all__ list 中包含该变量的名称。 .这是一种代码内文档形式。
关于python - 在 Python 的构造函数中使用 self._variable 和仅使用 self.variable 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27974997/