Python 具命元组不能替换值的问题?
from collections import namedtuple
TOP = namedtuple("TOP", ["database", "user"], defaults=[None, None])
Database_Container = namedtuple("Database_Container", ["engine", "session"])
big = TOP("1","2")
d = Database_Container(engine="123", session="123")
big._replace(database=d)
print(big)
- 如示例显示我调用了命名元组的
_replace
方法但是为什么值却没有改变呢
回复
1个回答

test
2024-06-28
https://docs.python.org/3/library/collections.html#collection...
somenamedtuple._replace(**kwargs)
Return a new instance of the named tuple replacing specified fields with new values:
_replace
并不是改变当前对象,而是返回一个新对象。
你可以用 big = big._replace(...)
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容