在运行时从字符串创建namedtuple实例(反射/动态创建)

时间:2017-10-21 20:07:01

标签: python-3.x reflection runtime namedtuple

如何动态创建namedtuple的实例?有可能吗?

Msg = collections.namedtuple('Msg', 'a b c')
...
mymsg = Msg(a=1,b=2,c=3)
msg_as_dict = mymsg._asdict()
msg_as_dict['recover_name'] = type(mymsg).__name__

如何在运行时从msg['recover_name']创建Msg实例?

更新: 如何在运行时获取namedtuple的类型?意思是,从存在实例中获取“Msg”。

1 个答案:

答案 0 :(得分:1)

这将不需要反射:

def test_tuple_builder(self):
    from collections import namedtuple

    name = "Foo"
    attribs = "bar baz goo tar taz"
    values = [100, "Hello", -1, "World", "1968"]

    tpl_cls = namedtuple(name, attribs)
    foo = tpl_cls(*values)

    self.assertEqual(values[0], foo.bar)
    self.assertEqual(values[1], foo.baz)
    self.assertEqual(values[2], foo.goo)
    self.assertEqual(values[3], foo.tar)
    self.assertEqual(values[4], foo.taz)

    print("We always use '{baz}, {tar}' as an example.".format(baz=foo.baz, tar=foo.tar))

所有测试都通过并输出:

  

我们总是使用“Hello,World'举个例子。