假设您在Python中有一个公共方法,其主要目的是检索基础数据属性的值(即内部后备存储).该方法可以具有惰性评估逻辑等.属性是这种方法的示例.
然后,对于方法和数据属性使用相同的名称是自然的,除了数据属性的下划线前缀.例如 -
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
Run Code Online (Sandbox Code Playgroud)
(来自Python的"属性"文档)
但是,如果该方法是供内部使用的,那么有哪些首选约定,因此它本身以下划线为前缀?使用两个前导下划线前缀后备存储将调用名称修改,因此不太理想.
有两种可能性 -
def _get_x(self):
return self._x
def _x(self):
return self._x_
Run Code Online (Sandbox Code Playgroud)
Python样式说第二个(附加下划线),应该只用于避免与保留关键字冲突.
首选的约定是使用单个前划线。
这是针对私有属性的PEP 8建议。
请参阅文档字符串中的以下有关property()的示例:
>>> help(property)
Help on class property in module builtins:
class property(object)
| property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
|
| fget is a function to be used for getting an attribute value, and likewise
| fset is a function for setting, and fdel a function for del'ing, an
| attribute. Typical use is to define a managed attribute x:
| class C(object):
| def getx(self): return self._x
| def setx(self, value): self._x = value
| def delx(self): del self._x
| x = property(getx, setx, delx, "I'm the 'x' property.")
|
| Decorators make defining new properties or modifying existing ones easy:
| class C(object):
| @property
| def x(self): return self._x
| @x.setter
| def x(self, value): self._x = value
| @x.deleter
| def x(self): del self._x
|
Run Code Online (Sandbox Code Playgroud)
如果它是供内部使用,为什么要将其设为财产?如果供内部使用,直接访问该属性即可。
但是,您仍然可以使用一个下划线,但将其命名为其他名称。但同样,在这种情况下,将其作为财产的全部意义就消失了。