简体   繁体   English

Function设置namedtuple属性?

[英]Function to set namedtuple attributes?

I have a namedtuple that's a private property of a class instance.我有一个 namedtuple,它是 class 实例的私有属性。 I want to create a new tuple based off an instance's namedtuple, but tuples are immutable, so I create a new one and just insert what I want.我想基于实例的命名元组创建一个新元组,但元组是不可变的,所以我创建一个新元组并插入我想要的内容。 Is there a better way of doing this?有更好的方法吗? It's extremely redundant, and I would like a specific function or so that would just take a namedtuple as a parameter and as the other parameter the attribute you want to change and it returns the new namedtuple.这是非常多余的,我想要一个特定的 function 左右,它只需要一个 namedtuple 作为参数,另一个参数是你想要更改的属性,它返回新的 namedtuple。 What would this look like?这会是什么样子?

There's a _replace method for that:有一个_replace方法:

new_namedtuple = old_namedtuple._replace(field_name=new_value)

Plus, it'll avoid the bug in your current code, where if two fields share the same value, your code might end up replacing the wrong one.另外,它会避免当前代码中的错误,如果两个字段共享相同的值,您的代码可能最终会替换错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM