【发布时间】:2019-02-20 18:39:24
【问题描述】:
如您所知,implementing a __getitem__ method makes a class iterable:
class IterableDemo:
def __getitem__(self, index):
if index > 3:
raise IndexError
return index
demo = IterableDemo()
print(demo[2]) # 2
print(list(demo)) # [0, 1, 2, 3]
print(hasattr(demo, '__iter__')) # False
但是,这不适用于正则表达式匹配对象:
>>> import re
>>> match = re.match('(ab)c', 'abc')
>>> match[0]
'abc'
>>> match[1]
'ab'
>>> list(match)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_sre.SRE_Match' object is not iterable
值得注意的是,__iter__ 方法中没有抛出此异常,因为该方法甚至没有实现:
>>> hasattr(match, '__iter__')
False
那么,如何在不使类可迭代的情况下实现__getitem__?
【问题讨论】:
-
我什至无法下标
match... -
@Sweeper
Match.__getitem__被添加到 Python 3.6 docs.python.org/3/library/re.html#re.Match.__getitem__ -
@DeepSpace 啊...我使用的是 3.5。
-
@PedroLobito 但这没有解释吗?
-
@PedroLobito 这是一个完全不同的问题,不是吗?我的匹配对象确实有一个
__getitem__方法...