python - 是否使用 __getattribute__ 来命名元组 : bad practice?

标签 python namedtuple getattribute

我正在探索用命名元组替换大量小字典的可能性。

因为字典键(字符串)已映射到命名元组的字段名称,所以我必须使用命名元组的 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/

相关文章:

python - 在 python3 上安装 socketio 模块似乎正在破坏 pip

python - 如何将二维列表转换为二维 numpy 数组?

python - 从 namedtuple 属性创建新列表

python - set() 中可以使用命名元组吗?

JavaScript - 更改一组包含特定文本和可变 ID 元素的链接

python - 张量的 Tensorflow "map operation"?

python - 给定一个带有元组键的 python 字典,正确格式化字符串

Pythonic 按字段名称对命名元组列表进行排序的方法

java - 当 Java Selenium 的代码片段中没有 "value"属性或文本时,如何将电子邮件/文本输入到字段中

php - 通过 DOM 或 XPATH 获取每个元素属性的宽度和高度