Python使用協議(使用特殊命名方法進行鴨式打印,使用雙下劃線前後固定)。 Java中的等價物將是一個接口或抽象基類。
在這種情況下,在Python中的任何一個實現the iterator
protocol可以在for
循環使用:
class TheStandardProtocol(object):
def __init__(self):
self.i = 0
def __iter__(self):
return self
def __next__(self):
self.i += 1
if self.i > 15: raise StopIteration()
return self.i
# In Python 2 `next` is the only protocol method without double underscores
next = __next__
class TheListProtocol(object):
"""A less common option, but still valid"""
def __getitem__(self, index):
if index > 15: raise IndexError()
return index
然後,我們可以使用兩種類的實例在for
循環,一切都將正常工作:
standard = TheStandardProtocol()
for i in standard: # `__iter__` invoked to get the iterator
# `__next__` invoked and its return value bound to `i`
# until the underlying iterator returned by `__iter__`
# raises a StopIteration exception
print i
# prints 1 to 15
list_protocol = TheListProtocol()
for x in list_protocol: # Python creates an iterator for us
# `__getitem__` is invoked with ascending integers
# and the return value bound to `x`
# until the instance raises an IndexError
print x
# prints 0 to 15
Java中的等價物是Iterable
和Iterator
接口:
class MyIterator implements Iterable<Integer>, Iterator<Integer> {
private Integer i = 0;
public Iterator<Integer> iterator() {
return this;
}
public boolean hasNext() {
return i < 16;
}
public Integer next() {
return i++;
}
}
// Elsewhere
MyIterator anIterator = new MyIterator();
for(Integer x: anIterator) {
System.out.println(x.toString());
}
謝謝。那回答那部分。 – freemann098
我發現它們與各種語言中的for-each循環非常相似。 –
它基本上與Java或C++ 11中的for(int number:my_list)相同。 C#可能有類似的東西。 – user2357112