2024-06-01 04:21:23 发布
网友
假设A是一个包目录,B是目录中的模块,X是用B编写的函数或变量?以scipy为例:
我想要的:
from scipy.constants.constants import yotta
什么不起作用:
如有任何建议,将不胜感激。在
python import语句执行两个任务:加载模块并使其在命名空间中可用。在
import foo.bar.baz
将在命名空间中提供名称foo,而不是baz,因此__import__将给您foo
foo
baz
__import__
另一方面
from foo.bar.baz import a, b
不使模块可用,但是import语句需要执行assignmaents是baz。这对应于
_tmp_baz = __import__('foo.bar.baz', fromlist=['a', 'b']) a = _tmp_baz.a b = _tmp_baz.b
当然,没有让临时的东西可见。在
__import__函数不强制a和b,所以当你想要baz时,你可以在fromlist参数中给出任何东西来将__import__置于“from input”模式。在
a
b
所以解决办法如下。假设'yotta'是一个字符串变量,我已经使用getattr来访问属性。在
getattr
yotta = getattr(__import__('scipy.constants.constants', fromlist=['yotta']), 'yotta')
__import__("scipy.constants.constants", fromlist=["yotta"])
参数fromlist相当于from LHS import RHS的右侧。在
fromlist
from LHS import RHS
From the docs:
__import__(name[, globals[, locals[, fromlist[, level]]]])[...]The fromlist gives the names of objects or submodules that should be imported from the module given by name.[...]On the other hand, the statement from spam.ham import eggs, sausage as saus results in_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) eggs = _temp.eggs saus = _temp.sausage
__import__(name[, globals[, locals[, fromlist[, level]]]])
[...]
The fromlist gives the names of objects or submodules that should be imported from the module given by name.
name
On the other hand, the statement from spam.ham import eggs, sausage as saus results in
from spam.ham import eggs, sausage as saus
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1) eggs = _temp.eggs saus = _temp.sausage
(重点是我的。)
python import语句执行两个任务:加载模块并使其在命名空间中可用。在
将在命名空间中提供名称
^{pr2}$foo
,而不是baz
,因此__import__
将给您foo
另一方面
不使模块可用,但是import语句需要执行assignmaents是baz。这对应于
当然,没有让临时的东西可见。在
__import__
函数不强制a
和b
,所以当你想要baz
时,你可以在fromlist参数中给出任何东西来将__import__
置于“from input”模式。在所以解决办法如下。假设'yotta'是一个字符串变量,我已经使用
getattr
来访问属性。在参数
fromlist
相当于from LHS import RHS
的右侧。在From the docs:
(重点是我的。)
相关问题 更多 >
编程相关推荐