我正在探索用命名元组替换大量小字典的可能性。
因为字典键(字符串)已映射到命名元组的字段名称,所以我必须使用命名元组的 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.
那是错误的工具。您应该使用 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)
关于python - 是否使用 __getattribute__ 来命名元组 : bad practice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725106/