python - 在私有(private)类前加上下划线是约定俗成的吗?

标签 python

我见过函数/常量以下划线为前缀的代码。 我的理解是,这表明它们不能直接使用。 我可以在类里面做到这一点吗?

class _Foo(object):
    pass

class __Bar(object):
    pass

最佳答案

最好只使用一个 _ .这表明名称在模块中是私有(private)的。

它不是用包罗万象的方式导入的 from <module> import * ,它还有一些其他的特性,比如“优先销毁”。

来自 here :

If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_').

来自 here :

Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted.

双下划线起始类(class)成员是name-mangled .

关于python - 在私有(private)类前加上下划线是约定俗成的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7609508/

相关文章:

python - 更新快速变化的目录中的文件路径列表

python - 如何在 python 中的 for 循环中跳过函数内的迭代步骤?

python - **SQLAlchemy** :Get a count of one column where another column is distinct

python - 导入到 Python 时的 excel.csv 文件舍入问题

来自 Git 存储库的 python setup.py sdist

python - 返回组中所有唯一的聚合

Python目录调用

python - 仅模拟对方法的所有调用的一个子集

python - Numpy:如何快速替换矩阵中的相等值?

python - 使用 Pandas 检查 2 个系列中的一对值的最有效方法?