python如何导入函数_如何正确使用python的导入函数__import __()

文档 H2>

__import__的文档是内置函数中最差的。

__import__(...)

__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module

Import a module. Because this function is meant for use by the Python

interpreter and not for general use it is better to use

importlib.import_module() to programmatically import a module.

The globals argument is only used to determine the context;

they are not modified. The locals argument is unused. The fromlist

should be a list of names to emulate ``from name import ...'', or an

empty list to emulate ``import name''.

When importing a module from a package, note that __import__('A.B', ...)

returns package A when fromlist is empty, but its submodule B when

fromlist is not empty. Level is used to determine whether to perform

absolute or relative imports. 0 is absolute while a positive number

is the number of parent directories to search relative to the current module.如果仔细阅读,您会发现API最初旨在允许从模块中延迟加载函数。但是,这不是CPython的工作方式,而且我不知道Python的任何其他实现是否已成功实现。

相反,CPython在第一次导入时执行模块命名空间中的所有代码,之后模块缓存在sys.modules中。

__import__仍然有用。但是根据文档理解它的作用是相当困难的。

完全使用__import__ h2>

要调整完整功能以演示当前的__import__ API,这里是一个包装器函数,其中包含更清晰,更好的文档API。

def importer(name, root_package=False, relative_globals=None, level=0):

""" We only import modules, functions can be looked up on the module.

Usage:

from foo.bar import baz

>>> baz = importer('foo.bar.baz')

import foo.bar.baz

>>> foo = importer('foo.bar.baz', root_package=True)

>>> foo.bar.baz

from .. import baz (level = number of dots)

>>> baz = importer('baz', relative_globals=globals(), level=2)

"""

return __import__(name, locals=None, # locals has no use

globals=relative_globals,

fromlist=[] if root_package else [None],

level=level)为了证明,例如从姊妹套餐到巴兹:

baz = importer('foo.bar.baz')

foo = importer('foo.bar.baz', root_package=True)

baz2 = importer('bar.baz', relative_globals=globals(), level=2)

assert foo.bar.baz is baz is baz2

模块中名称的动态访问 h2>

要从baz模块按名称动态访问全局变量,请使用getattr。例如:

for name in dir(baz):

print(getattr(baz, name))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值