gpt4 book ai didi

python - 让 namedtuple 接受 kwargs

转载 作者:太空狗 更新时间:2023-10-29 20:37:02 24 4
gpt4 key购买 nike

如果我有这样的类(class):

class Person(object):
def __init__(self, name, **kwargs):
self.name = name

p = Person(name='joe', age=25) # age is ignored

忽略额外的参数。但是如果我有一个 namedtuple,我会得到“意外的关键字参数:

from collections import namedtuple 

Person = namedtuple('Person', 'name')
p = Person(name='joe', age=25)

# Traceback (most recent call last):
# File "python", line 1, in <module>
# TypeError: __new__() got an unexpected keyword argument 'age'

如何让 namedtuple 接受 kwargs 以便我可以安全地传递额外的参数?

最佳答案

这不是很漂亮:

p = Person(*(dict(name='joe', age=25)[k] for k in Person._fields))

关于python - 让 namedtuple 接受 kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35727396/

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