对namedtuple使用\uugetattribute\uu:错误的做法吗?

2024-06-16 09:43:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在探索用namedtuples替换大量小字典的可能性。在

因为dict键(字符串)已经映射到namedtuples的字段名上,所以我必须使用namedtuple的dundered getattribute方法来访问这些值。在

这不仅使代码看起来有点奇怪,而且我还想知道这是否是一个坏的做法?在


Tags: 方法字符串代码字典可能性namedtupledict字段名
1条回答
网友
1楼 · 发布于 2024-06-16 09:43:43

Because dict keys (strings) have been mapped onto the field names of the namedtuples, I have to make use of the dundered getattribute method of the namedtuple to access the values.

那是错误的工具。您应该使用^{}内置函数,而不是__getattribute__方法:

getattr(your_namedtuple, attribute_name)

也就是说,如果您想主要通过名称而不是索引来访问数据,那么一直调用getattr会很尴尬。您可以将namedtuple类的子类化,并更改__getitem__的工作方式,以便仍然可以使用索引表示法:

^{pr2}$

相关问题 更多 >