无论如何要限制模块中的方法在 python 中导入?
is there anyway to restrict a method in module from import in python?
我有一个 python 目录,如下所示。在 test.py 中,我有 a、b、c 方法。
虽然导入测试我不希望用户导入 c 方法。一种方法是将 as c 方法设为私有。无论如何在 __init__.py
或使用 __import__
中实现这一点
test
__init__.py
test.py
我在 Whosebug 中看到的解决方案很少,但我没有办法实现它。
谢谢。
如果您正在寻找绝对私有方法,那么 python 是不适合您的语言 - 请转至 Java 或 C/++/# 或其他支持区分的语言在 public
和 private
之间。在 python 中,如果知道某物存在,那么无论它有多隐蔽,通常都可以访问它。
如果您只是想在用户导入您的模块时限制 方便的选项 ,那么您可以简单地选择性地包含或排除 __init__.py
中的方法.说你有
test.py
def a():
pass
def b():
pass
def c():
pass
并且您希望用户可以访问 a
和 b
但 c
不是,那么您可以
__init__.py
from .test import a, b
并将文件夹导出为模块。现在,当用户
import test
他们只能访问 __init__.py
结束时命名空间中的内容(也就是说,他们可以获得 test.a
和 test.b
,但 test.c
不存在)。由于您从未在 __init__.py
中包含 c
,它不会出现在那里。
请注意,c
仍然可以通过
访问
from test.test import c
直接访问源文件。
或者,您可以在每个文件的基础上指定哪些名称应该可以通过使用内置变量__all__
立即访问。以下将与上述代码具有相同的效果:
test.py
...
__all__ = ['a', 'b'] # note that 'c' is excluded
__init__.py
from test.py import * # imports a and b, but not c
我有一个 python 目录,如下所示。在 test.py 中,我有 a、b、c 方法。
虽然导入测试我不希望用户导入 c 方法。一种方法是将 as c 方法设为私有。无论如何在 __init__.py
或使用 __import__
test
__init__.py
test.py
我在 Whosebug 中看到的解决方案很少,但我没有办法实现它。
谢谢。
如果您正在寻找绝对私有方法,那么 python 是不适合您的语言 - 请转至 Java 或 C/++/# 或其他支持区分的语言在 public
和 private
之间。在 python 中,如果知道某物存在,那么无论它有多隐蔽,通常都可以访问它。
如果您只是想在用户导入您的模块时限制 方便的选项 ,那么您可以简单地选择性地包含或排除 __init__.py
中的方法.说你有
test.py
def a():
pass
def b():
pass
def c():
pass
并且您希望用户可以访问 a
和 b
但 c
不是,那么您可以
__init__.py
from .test import a, b
并将文件夹导出为模块。现在,当用户
import test
他们只能访问 __init__.py
结束时命名空间中的内容(也就是说,他们可以获得 test.a
和 test.b
,但 test.c
不存在)。由于您从未在 __init__.py
中包含 c
,它不会出现在那里。
请注意,c
仍然可以通过
from test.test import c
直接访问源文件。
或者,您可以在每个文件的基础上指定哪些名称应该可以通过使用内置变量__all__
立即访问。以下将与上述代码具有相同的效果:
test.py
...
__all__ = ['a', 'b'] # note that 'c' is excluded
__init__.py
from test.py import * # imports a and b, but not c