而不是定义
from numpy import cos as cos
from numpy import arccos as arccos
等等,我能不能写点
trigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')
for method in trigfunctions:
setattr(HERE,method,getattr(numpy,method))
其中HERE
是全局空间(或可能是局部函数环境)?这样可以更容易地定义基于cos
、arccos
的通用函数,而无需指定名称空间,并从所需模块加载适当的函数(例如,如果numpy
不可用,则加载math
)。我意识到,在非常普遍的情况下,这可能会导致错误,但在一些小的情况下,它是有用的。
如果您的意思是导入相同的名称,只需省略as
:
from numpy import cos, arccos, sin, arcsin, tan, arctan
除此之外,您可以使用globals()
来获取当前模块的符号表:
me=globals();
trigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')
for method in trigfunctions:
me[method] = numpy.__dict__[method]
您也可以使用sys.modules[__name__]
来引用当前模块