python - 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
解决方案
下划线规则是进口商在看到from test_var import *
. 事实上,这些函数仍在模块命名空间中,您仍然可以使用它们:
import test_var
test_var._test_func()
您不导入类方法,只导入类,因此不应用下划线规则。p1._check_func()
工作原理与工作原理相同test_var._test_func()
:您在其命名空间中处理了变量。
推荐阅读
- css - 将 Angular Material 选项卡正文内容向左对齐
- css - 在动画部分之间切换
- c# - 我怎样才能使干净的表单按钮点击用完任何事件或条件?
- java - 如何从 Java 程序中调用 Oracle 函数
- php - Laravel 使用 GET 方法进行身份验证
- asp.net - 是否可以像 Angular 一样制作 ASP.NET url,即 localhost:5000/#/etc?
- sockets - 客户端上的套接字错误
, 断开 - java - 为什么有时可以有时不能在android oppo上捕获图像
- hellosign-api - HelloSign:如何解决 SameOrigin 错误?
- html - 无论如何,在 Internet Explorer 中没有 activeX 的情况下从本地文件目录加载 pdf 吗?