gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:46:17 24 4
gpt4 key购买 nike

如何动态创建命名元组的实例?可能吗?

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 的类型?意思是,从现有实例中获取“消息”。

最佳答案

这将在不需要反射的情况下工作:

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))

所有测试通过,输出:

We always use 'Hello, World' as an example.

关于python-3.x - 在运行时从字符串创建 namedtuple 实例(反射/动态创建),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46867573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com