2024-06-16 09:43:43 发布
网友
我正在探索用namedtuples替换大量小字典的可能性。在
因为dict键(字符串)已经映射到namedtuples的字段名上,所以我必须使用namedtuple的dundered getattribute方法来访问这些值。在
这不仅使代码看起来有点奇怪,而且我还想知道这是否是一个坏的做法?在
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__方法:
__getattribute__
getattr(your_namedtuple, attribute_name)
也就是说,如果您想主要通过名称而不是索引来访问数据,那么一直调用getattr会很尴尬。您可以将namedtuple类的子类化,并更改__getitem__的工作方式,以便仍然可以使用索引表示法:
getattr
namedtuple
__getitem__
那是错误的工具。您应该使用^{} 内置函数,而不是
__getattribute__
方法:也就是说,如果您想主要通过名称而不是索引来访问数据,那么一直调用
^{pr2}$getattr
会很尴尬。您可以将namedtuple
类的子类化,并更改__getitem__
的工作方式,以便仍然可以使用索引表示法:相关问题 更多 >
编程相关推荐