从string中提取函数参数

时间:2017-11-13 01:09:08

标签: python

我有以下内容:

mystring="myobject"
def foo(object):
    pass

我想直接使用foo(myobject)致电mystring,方式与getattr(myclass, "mymethod")相同。

欢迎任何帮助。感谢

1 个答案:

答案 0 :(得分:1)

You can resolve the value of myobjectfrom the module where it is defined with getattr. If it is in the main module, this should work:

import __main__

mystring = 'This is a test.'

def foo(object):
    print object

variableName = 'mystring'
foo(getattr(__main__, variableName))
variableName = 'variableName'
foo(getattr(__main__, variableName))

This should print

This is a test.

variableName

The import of the main module is necessary for variables from the main scope.

Edit: You can also get the content of the string with very dangerous eval(). Just replace foo(getattr(__main__, variableName)) with foo(eval(variableName)).