当使用迭代器的数据时,每次从数据流中取一个数据,直到被取完,而且不会重复.
迭代器协议方法主要是__iter__和__next__,在无下一个元素的时候会引发StopIteration异常停止迭代
那么现在来自定义一个迭代器
class MyIterator: #自定义迭代器的类
def __init__(self,x=2,xmax=100): #定义构造方法,初始化
self.__mul,self.__x=x,x
self.__xmax=xmax
def __iter__(self): #定义迭代器协议方法
return self
def __next__(self): #定义迭代器协议方法
if self.__x and self.__x !=1:
self.__mul *= self.__x
if self.__mul <=self.__xmax:
return self.__mul #返回值
else:
raise StopIteration #引发错误停止迭代
else:
raise StopIteration
if __name__ == '__main__':
b=B()
myiter=MyIterator()
for i in myiter:
print("迭代的元素为:",i)
输出如下
这样就定义了一个迭代器了,在python里用__命名变量是私有化命名,在命名方面python也是蛮有意思的,可参看https://blog.youkuaiyun.com/warm77/article/details/78353632,搜索引擎上也有很多,这里举一个很有典型的私有成员的例子:
class A(object):
def __init__(self):
print("astart")
self.__private()
self.public()
def __private(self):
print("a.private")
def pubilc():
print("a.pbulic")
class B(A):
def private(self):
print("Bprivate")
def public(self):
print("b public")
b=B()
猜猜输出了什么,
a.private
b public
能不能理解呢,这里就不做更多的拓展了