使用 __getitem__ 进行索引和键访问

问题描述 投票:0回答:0

我有一个自定义类,访问属性是有意义的,就像访问元组或字典的类一样。

(该类是带有子单位的度量单位的通用类。例如,以码、英尺和英寸为单位的长度,或以度、分和秒为单位的角度。)

我已经将类设置为能够在运行时接受任何一组属性名称,并且这些名称的列表存储在类中。可以使用点表示法访问属性。 (并没有改变,因为我覆盖了

__setattr__
方法。)然后我设置类能够从带有
__getitem__
的下标访问项目,并添加了接受
slice
索引的条件。我突然想到,
__getitem__
方法可以用作
dict
所在的类,并接受属性名称。

这里是相关代码:

class MeasureWithSubunits():
    units = ('days', 'hours', 'minutes')
    # Class variable can be assigned as normal at runtime.
    # Assigned here as an example.
    
    def __init__(self, *args) -> None:
        # Tidy up the input
        ...
        for i, unit in enumerate(self.units):
            self.__dict__[unit] = args[i] if i < len(args) else 0
    
    def __getitem__(self, index):
        if type(index) is int:
            return self.__dict__[self.units[index]]
        elif type(index) is slice:
            return [self.__dict__[self.units[i]] for i in range(
                    index.start or 0,
                    index.stop or len(self.units),
                    index.step or 1
                   )]
        else:
            return self.__dict__[index]

    def __len__(self) -> int:
        return len(self.units)

    def __setattr__(self, name, attr_value):
        raise AttributeError("Does not support attribute assignment")

我的问题是,允许方括号访问同时用于这两种几乎矛盾的方式是“错误的”吗?特别是考虑到密钥访问方法是不必要的,因为已经提供了点访问。

为了避免成为一个意见问题,我想要一个基于文档的答案。 (并不是说我会介意一个很好的观点。)

python magic-methods
© www.soinside.com 2019 - 2024. All rights reserved.