将字符串解释为参数中的代码

时间:2014-11-13 12:21:28

标签: python dynamic parameters

阿罗哈,我有以下课程:

class Foo(object):

    def __init__(self, **kwargs):
        ''' set variable attributes to self '''

        for key, value in kwargs.items():
            setattr(self, key, value)

现在我有了这个字符串:

x = 'a=100, b=200, c=300'

我尝试过这样的事情:

y = Foo(exec(x))
# or
y = Foo(eval(x))

# should work like this

y = Foo(a=100, b=200, c=300)

但这不起作用。如何将这样的字符串解释为参数切换?


解决方案:

https://stackoverflow.com/users/3001761/jonrsharpe

引导
class Foo(object):
    @classmethod
    def from_string(cls, arg_str):
        arg_dict = eval('dict({})'.format(arg_str.replace(' ', ',')))
        new_cls = cls()
        for key, value in arg_dict.items():
            setattr(new_cls, key, value)
        return new_cls

x = 'a=100 b=200 c=300'

foo = Foo.from_string(x)

0 个答案:

没有答案