在 Python 的构造函数中使用 self._variable 和只使用 self.variable 有什么区别
What is the difference between using self._variable and just self.variable in the constructor in Python
例如,如果我创建一个 class 点。
class 点数:
def__init__(self, x, y):
self._x = x
self._y = y
和
class 点数:
def__init__(self, x, y):
self.x = x
self.y = y
使用 self._x 和 self.x 有什么区别?
单下划线只是一种命名约定,表示 属性 应被视为“半私有”(类似地,双下划线表示“私有”),但它没有语义差异:代码的两个版本的行为应该完全相同。根据 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 class FooBar
, __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 中包含该变量的名称.这是代码内文档的一种形式。
例如,如果我创建一个 class 点。
class 点数:
def__init__(self, x, y):
self._x = x
self._y = y
和
class 点数:
def__init__(self, x, y):
self.x = x
self.y = y
使用 self._x 和 self.x 有什么区别?
单下划线只是一种命名约定,表示 属性 应被视为“半私有”(类似地,双下划线表示“私有”),但它没有语义差异:代码的两个版本的行为应该完全相同。根据 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 中包含该变量的名称.这是代码内文档的一种形式。