覆盖嵌套列表的__getitem__?

时间:2015-07-09 20:13:10

标签: python operator-overloading qr-code

我正在实施一个exerimental QR代码解析器,我认为覆盖列表的__getitem__是很方便的,它会考虑给定的掩码,如下所示:

m = [[1, 0], [0, 1]]
def mask(m, i, j):
  if i % 2 == 0 or j == 0:
    return int(not m[i][j])
  return m[i][j]
m2 = list_with_mask(m, mask)
n = m2[0][0]

我怎样才能以最恐怖的方式实现它?

1 个答案:

答案 0 :(得分:0)

快速而肮脏的实现,也许最好从内置的list类继承。
不是直接问OP,而是至少是一个开始,您可以根据需要自定义它。

    class CustomNestedObject:
        """Custom weird class to handle __getitem__

        TODO: add error handling for strings and other non list/tuple objects
        """

        ERRORS = {
            'element_doesnt_exist': "You don't have element with such index"
        }

        def __init__(self, obj):
            self._nested = []       # will store nested recursive CustomNestedObject(s)
            self._value = None      # will store value (for example integer or string)
            # recursively parse obj to CustomNestedObject
            self._parse_to_self(obj)

        def __repr__(self):
            """Method which will return string representation for the nested objects or self._value"""
            if not self._nested:
                return str(self._value)
            else:
                return str([x._value for x in self._nested])

        def __getitem__(self, index):
            # handle error
            try:
                self._nested[index]
            except IndexError:
                raise Exception(self.ERRORS['element_doesnt_exist'])
            if not self._nested[index]._nested:
                # it means that returned object will be self.value
                # print(f'trying to access {self._nested[index]._value}')
                return self._nested[index]._value
            else:
                # print('trying to access nested object')
                return self._nested[index]

        def _parse_to_self(self, obj):
            if isinstance(obj, list) or isinstance(obj, tuple):
                for item in obj:
                    self._nested.append(CustomNestedObject(item))
            else:
                # save as number if obj is not a list or tuple
                self._value = obj


    if __name__ == '__main__':
        x = CustomNestedObject([1, 2, 3, [4, 5]])
        print(x[3][1])
        print(x[0])
        print(x[9])