网络编程
位置:首页>> 网络编程>> Python编程>> python 将对象设置为可迭代的两种实现方法

python 将对象设置为可迭代的两种实现方法

作者:ZhanYunQI  发布时间:2023-08-24 18:01:39 

标签:python,对象,可迭代

1、实现 __getitem__(self)


class Library(object):
 def __init__(self):
   self.value=['a','b','c','d','e']

def __getitem__(self, i):
   if i>=len(self.value):
     raise IndexError("out of index")
   value=self.value[i]
   return value

调用的时候,系统默认从0 开始传入,并使得i=i+1

2、实现 __iter__(self),next(self)


class Library2(object):
 def __init__(self):
   self.value=['a','b','c','d','e']
   self.i=-1
 def __iter__(self):
   return self
 def next(self):
   self.i += 1
   if self.i>=len(self.value):
     raise StopIteration
   return self.value[self.i]

test=Library2()
print test.next()
print test.next()

在这里可以像生成器一样使用

来源:https://blog.csdn.net/ZhanYunQI/article/details/70215678

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com