使用self.\u变量和just有什么区别自变量在Python的构造函数中

2024-10-17 21:38:37 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,如果我创建一个类点。在

课程点:

def__init__(self, x, y):
    self._x = x
    self._y = y 

以及

课程点:

^{pr2}$

self.x和just self.x的用法有什么区别


Tags: self用法initdef课程just区别pr2
1条回答
网友
1楼 · 发布于 2024-10-17 21:38:37

单下划线只是一种命名约定,用于声明属性应被视为“半私有”(类似地,双下划线表示“私有”),但它没有语义上的区别:两个版本的代码的行为应该完全相同。根据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中包含该变量的名称。这是代码内文档的一种形式。在

相关问题 更多 >