我想为可迭代容器委托(delegate) __iter__
方法。
class DelegateIterator:
def __init__(self, container):
attribute = "__iter__"
method = getattr(container, attribute)
setattr(self, attribute, method)
d = DelegateIterator([1,2,3])
for i in d.__iter__(): # this is successful
print(i)
for i in d: # raise error
print(i)
输出为
1
2
3
Traceback (most recent call last):
File "test.py", line 10, in <module>
for i in d:
TypeError: 'DelegateIterator' object is not iterable
请告诉我如何委托(delegate) __iter__
方法。
最佳答案
为什么让事情变得过于复杂?
class DelegateIterator:
def __init__(self, container):
self.container = container
def __iter__(self):
return iter(self.container)
关于python - 如何在Python中委托(delegate) `__iter__`方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66417196/