2022年 11月 8日

python列表迭代器_如何覆盖Python列表(迭代器)行为?

运行这个:

class DontList(object):

def __getitem__(self, key):

print ‘Getting item %s’ % key

if key == 10: raise KeyError(“You get the idea.”)

return None

def __getattr__(self, name):

print ‘Getting attr %s’ % name

return None

list(DontList())

产生这个:

Getting attr __length_hint__

Getting item 0

Getting item 1

Getting item 2

Getting item 3

Getting item 4

Getting item 5

Getting item 6

Getting item 7

Getting item 8

Getting item 9

Getting item 10

Traceback (most recent call last):

File “list.py”, line 11, in

list(DontList())

File “list.py”, line 4, in __getitem__

if key == 10: raise KeyError(“You get the idea.”)

KeyError: ‘You get the idea.’

我怎样才能改变它以便我得到[],同时仍允许访问这些键[1]等?

(我已尝试输入def __length_hint __(self):返回0,但它没有帮助.)

我的真实用例:(如果它有用的话,请仔细阅读;随意忽略这一点)

将a certain patch应用于iniparse之后,我发现了一个令人讨厌的副作用.在我的Undefined类上设置了__getattr__,它返回一个新的Undefined对象.不幸的是,这意味着list(iniconfig.invalid_section)(其中isinstance(iniconfig,iniparse.INIConfig))正在执行此操作(在__getattr__和__getitem__中放入简单的打印件):

Getting attr __length_hint__

Getting item 0

Getting item 1

Getting item 2

Getting item 3

Getting item 4

等等无限.