是使用__getAttribute__ for Nefuple:不良练习



我正在探索用命名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)

最新更新