栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

有没有办法在Python中访问父模块

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

有没有办法在Python中访问父模块

如果您已经访问了模块,则通常可以从

sys.modules
词典中访问它。Python不会使用名称保留“父指针”,特别是因为这种关系不是一对一的。例如,使用您的示例:

>>> from subprocess import types>>> types<module 'types' from '/opt/local/Library/frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc'>>>> import sys>>> sys.modules['subprocess']<module 'subprocess' from '/opt/local/Library/frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.pyc'>

如果你会注意到存在

types
的在
subprocess
模块只是一个假象
import types
在里面的语句。只要
importtypes
您需要该模块即可。

实际上,将来的版本

subprocess
可能不再导入
types
,并且您的代码将中断。您应该只导入出现在
__all__
模块列表中的名称;考虑其他名称作为实现细节。

因此,例如:

>>> import subprocess>>> dir(subprocess)['CalledProcessError', 'MAXFD', 'PIPE', 'Popen', 'STDOUT', '_PIPE_BUF', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_active', '_cleanup', '_demo_posix', '_demo_windows', '_eintr_retry_call', '_has_poll', 'call', 'check_call', 'check_output', 'errno', 'fcntl', 'gc', 'list2cmdline', 'mswindows', 'os', 'pickle', 'select', 'signal', 'sys', 'traceback', 'types']>>> subprocess.__all__['Popen', 'PIPE', 'STDOUT', 'call', 'check_call', 'check_output', 'CalledProcessError']

您可以看到其中可见的大多数名称

subprocess
只是它导入的其他顶级模块。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号