首页 > 解决方案 > Python类中带前导下划线的变量和函数的行为

问题描述

当我们使用时,除非模块/包的列表明确包含它们,否则不会导入from <module/package> import *以 a 开头的名称。___all__

这不适用于类的变量和函数吗?

从下面的程序来看,它似乎不适用于类中的变量和函数。

_bar并且_check_func两者都在test_import.py. 但是,_test_func()由于具有前导下划线而引发错误。我在这里错过了什么吗?

test_var.py

class test:
    def __init__(self):
        self._bar=15
    def test_mod(self):
        print("this is test mod function")
    def _check_func(self):
        print("this is _check_func function")

def _test_func():
    print("this is test function var 2")

test_import.py

from test_var import *

p1=test()
print(p1._bar)
p1.test_mod()
p1._check_func()

_test_func()

输出:

15
this is test mod function
this is _check_func function
Traceback (most recent call last):
  File "test_import.py", line 8, in <module>
    _test_func()
NameError: name '_test_func' is not defined

标签: python

解决方案


下划线规则是进口商在看到from test_var import *. 事实上,这些函数仍在模块命名空间中,您仍然可以使用它们:

import test_var
test_var._test_func()

您不导入类方法,只导入类,因此不应用下划线规则。p1._check_func()工作原理与工作原理相同test_var._test_func():您在其命名空间中处理了变量。


推荐阅读