是否可以使用变量作为变量的名称来调用函数?示例:
def my_method(foo="bar"):
print(foo)
var = "foo='baz'"
my_method(var)
>>> baz现在,我无法找到这样的方法(将变量中的值替换为变量名)。
这种事有可能吗?
我知道你可以做一些类似于这样的事情,例如:
def my_method(foo, bar, baz):
print(foo, bar, baz)
var = ['one','two','three']
my_method(*var)
>>> one two three但我在python中可能需要的任何元编程都找不到统一的、通用的解决方案。有一个吗?也许该语言只是无法提供一个通用的元编程解决方案。
发布于 2018-03-14 21:45:32
您可以为exec提供一个字典,它将在其中存储变量,然后将其解压缩为函数的关键字参数。
def my_method(foo="bar"):
print(foo)
var_a = "foo='baz'"
kwargs = {}
# See safety note at the bottom of this answer.
exec(var_a, {'__builtins__': {}}, kwargs)
my_method(**kwargs )
# prints: 'baz'您甚至可以使用装饰师将这种行为赋予函数。
def kwargs_as_string(f):
def wrapper(string, **more_kwargs):
kwargs = {}
# See safety note at the bottom of this answer.
exec(string, {'__builtins__': {}}, kwargs)
return f(**kwargs, **more_kwargs)
return wrapper
@kwargs_as_string
def my_method(foo="bar"):
print(foo)
my_method("foo='baz'")
# prints: 'baz'安全注意事项
为了安全起见,我们为exec提供了一个空的全局__builtins__,否则将在该键下插入对内置模块字典的引用。这会带来麻烦。
var_a = '__import__("sys").stdout.write("You are in trouble")'
exec(var_a, {}, {})
# prints: You are in trouble
exec(var_a, {'__builtins__': {}}, {})
# raises a NameError: name '__import__' is not defined发布于 2018-03-14 22:00:09
假设允许使用JSON格式的字符串..。
import json
args = json.loads(
"""
{
"kwargs": {
"a": 2,
"b": 1
},
"args": [3, 4]
}
""")
def foo(a, b):
print("a: {}".format(a))
print("b: {}".format(b))
foo(**args["kwargs"])
foo(*args["args"])
# output:
# a: 2
# b: 1
# a: 3
# b: 4发布于 2018-10-11 15:32:24
can you use getattr to call a function within your scope?
我发现这三种选择,最后一种对我来说是最有用的。
def foo():
def bar(baz):
print('dynamically called bar method using', baz)
packages = {'bar': bar}
getattr(packages['bar'], "__call__")('getattr with map')
packages['bar']('just the map')
locals()['bar']('just locals()')
foo()python test_dynamic_calling.py
dynamically called bar method using getattr with map
dynamically called bar method using just the map
dynamically called bar method using just locals()https://stackoverflow.com/questions/49288042
复制相似问题