[英]How can I get a named tuple instance from its name in python?
I have a set of named tuple instances.我有一组命名的元组实例。 Eg:例如:
CostFN = namedtuple('CostFN', ['name', 'func', 'args'])
tuple_lin_1 = CostFN(name="lin_1", args=args_for_1, func1=func_1)
tuple_lin_2 = CostFN(name="lin_2", args=args_for_1, func1=func_2)
tuple_lin_3 = CostFN(name="lin_3", args=args_for_2, func1=func_1)
tuple_lin_4 = CostFN(name="lin_4", args=args_for_2, func1=func_2)
I am saving the instance name, and I want to access the relevant instance from its name.我正在保存实例名称,并且我想从其名称访问相关实例。 Something like: my_tuple = CostFN.get("lin4")
How do I achieve that?类似于: my_tuple = CostFN.get("lin4")
我该如何实现?
You can't in any reasonable way.你不能以任何合理的方式。 Objects don't have names in the way you think they do, names are bound to objects.对象没有在你认为他们这样做,名字被绑定到对象的方式名称。 So tuple_lin_4
is a name that contains a binding to the associated instance of CostFN
, but the instance has no idea it's bound to that name.所以tuple_lin_4
是一个名称,它包含与CostFN
的关联实例的CostFN
,但该实例不知道它绑定到该名称。 Similarly, the instance knows it is of type CostFN
, but CostFN
doesn't know about its own instances.同样,实例知道它是CostFN
类型,但CostFN
不知道它自己的实例。 So you've got two layers where the linkages don't work the way you intend.因此,您有两层,其中的链接无法按您预期的方式工作。
If looking up instances by name is an issue, I'd suggest making a dict
mapping names to instances, rather than using individual named variables.如果按名称查找实例是一个问题,我建议你做一个dict
映射名称的情况下,而不是使用单独的命名变量。 If you really wanted to, you could do terrible things with a custom __new__
to cache instances by name on a dict
tied to the class, but frankly, even that's going too far;如果您真的想这样做,您可以使用自定义__new__
做一些糟糕的事情,以在与类相关的dict
上按名称缓存实例,但坦率地说,即使这样也太过分了; you likely have an XY problem if you think you need a behavior like this at all.如果您认为您完全需要这样的行为,您可能会遇到 XY 问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.