[英]accessing module-level functions in Python if their name is stored in a variable
What is the best way to use a function at the top of a module if do not know the name of the object in advance: The function might depend on user input and hence its name is stored in a variable. 如果事先不知道对象的名称,那么在模块顶部使用函数的最佳方法是什么:该函数可能取决于用户输入,因此其名称存储在变量中。
One solution uses eval() : For example, in ScipyCookbook/SignalSmooth: smooth() (also referenced in an answer to StackOverflow: Python Smooth Time Series Data ) 一种解决方案使用eval() :例如,在ScipyCookbook / SignalSmooth中:smooth() (也在StackOverflow的答案:Python平滑时间序列数据中引用)
import numpy
window = 'hanning'
w = eval('numpy.'+window+'(11)')
will be equivalent to 相当于
w = numpy.hanning(11)
However, is there a better method than using fragile/potentially dangerous eval
? 但是,有没有比使用脆弱/潜在危险的
eval
更好的方法?
For instance, wouldn't using vars() 例如,不会使用vars()
w = vars(numpy)[window](11)
be preferred? 被首选? Any better/more pythonic ideas?
还有更好/更多的Python想法吗?
You should use a dictionary mapping the valid window function names to the actual functions: 您应该使用将有效的窗口函数名称映射到实际函数的字典:
windows = {"bartlett": numpy.bartlett,
"blackman": numpy.blackman,
"hamming": numpy.hamming,
"hanning": numpy.hanning,
"kaiser": numpy.kaiser}
If you use eval()
, the user is basically allowed to execute arbitrary code. 如果使用
eval()
,则基本上允许用户执行任意代码。
The variant 变体
w = vars(numpy)[window](11)
is definitely better than using eval()
, but it still does not make sure the function the user selected makes sense in the given context. 绝对比使用
eval()
更好,但是仍然不能确保用户选择的功能在给定上下文中有意义。 (And usually, you'd use getattr()
for this instead.) (通常,您可以使用
getattr()
代替。)
A module's functions are attributes of the module, so you can do: 模块的功能是模块的属性,因此您可以执行以下操作:
window = "hanning"
getattr(numpy, window)(11)
vars()
is also fine. vars()
也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.