Mat*_* G. 0 python python-import
假设我编写了一个名为的 python 模块my_module:
# my_module.py
import numpy as np
def my_function():
print("Hello, module!")
Run Code Online (Sandbox Code Playgroud)
然后我my_module使用内置函数导入并检查它dir():
>>> import my_module
>>> dir(my_module)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'my_function', 'np']
Run Code Online (Sandbox Code Playgroud)
np显示在由 定义的名称列表中my_module。这很烦人,因为我经常想dir()通过my_module. 但是在上面的结果中,我不清楚如何判断它np是本地的my_module还是只是my_module导入的某个包,这(在我看来)混淆了my_module.
所以我的问题是,我如何构建my_module以便只有它定义的函数/类/等出现dir(my_module)?或者等效地,这样dir(my_module)就不会打印出导入的每个模块my_module.py?
我想:
这是可能的,因为dir(other popular packages)通常不会列出他们的每个导入:
>>> import scipy
>>> print([x for x in dir(scipy) if "np" in x])
['nanpercentile', 'nanprod', 'nper', 'npv', 'unpackbits']
>>> print([x for x in dir(scipy) if "numpy" in x])
['__numpy_version__', 'show_numpy_config']
Run Code Online (Sandbox Code Playgroud)
或者也许他们这样做了,而这个事实刚刚从我身上逃脱,
或者我可能以dir()非预期的方式使用,没有人关心是否有一堆导入出现在 中dir(my_module),这是浪费时间。
从dir文档:
如果对象是模块对象,则列表包含模块属性的名称。
导入的模块是属性,因此出现在列表中。但这可以被覆盖
如果对象有一个名为dir () 的方法,这个方法将被调用并且必须返回属性列表。
所以你可以dir通过编写一个返回你想要的函数来得到你想要的。
# my_module.py
import numpy as np
def my_function():
print("Hello, module!")
def __dir__():
return ["my_function"]
Run Code Online (Sandbox Code Playgroud)
但这很容易出错……你必须跟上清单。我认为更好的方法是使用 python 的文档字符串并提供帮助。这就是它的用途。您可以控制您的文档应该多健谈。
"""My module
Filled with my things.
"""
import numpy as np
def my_function():
"""Print the message"""
print("Hello, module!")
Run Code Online (Sandbox Code Playgroud)
例子
>>> import my_module
>>> help(my_module)
Help on module my_module:
NAME
my_module - My module
DESCRIPTION
Filled with my things.
FUNCTIONS
my_function()
Print the message
FILE
/home/td/tmp/a/my_module.py
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |