为嵌套列表覆盖__getitem__吗? [英] Overriding __getitem__ for a nested list?

查看:79
本文介绍了为嵌套列表覆盖__getitem__吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个实验QR码解析器,我认为覆盖一个考虑了给定掩码的列表的__getitem__会很方便,就像这样:

I'm implementing an exerimental QR code parser and I figured it would be handy to override a list's __getitem__ that takes a given mask into account, like this:

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]

如何以最Python的方式实现它?

How can I achieve it in the most Pythonic way?

推荐答案

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

Quick & dirty implementation, maybe it's better to inherit from the built-in list class.
Not directly what OP asked but but at least it's a start, and you can customize it for your needs.

    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])

这篇关于为嵌套列表覆盖__getitem__吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆