我正在探索用命名tuplame代替大量小词典的可能性。
由于dict键(字符串)已映射到命名图的字段名称上,所以我必须使用命名tuple的扣留的getAttribute方法来访问值。
这不仅使代码看起来有点奇怪,而且我也想知道这是否是不良练习?
由于dict键(字符串)已映射到命名图的字段名称上,所以我必须使用命名tuple的扣留的getAttribute方法来访问值。
那是错误的工具。您应该使用getattr
内置功能,而不是__getattribute__
方法:
getattr(your_namedtuple, attribute_name)
也就是说,如果您要主要通过名称而不是索引访问您的数据,请一直调用getattr
会很尴尬。您可以子类namedtuple
类并更改__getitem__
的工作方式,因此您仍然可以使用索引符号:
class MyType(namedtuple(...)):
__slots__ = () # avoid creating instance __dict__s
def __getitem__(self, index):
try:
return super().__getitem__(index)
except TypeError:
return getattr(self, index)