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

yipeiwu_com6年前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()

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

以上这篇python 将对象设置为可迭代的两种实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python调用c++返回带成员指针的类指针实例

这个是OK的: class Rtmp_tool { public: int m_width; AVCodecContext * c; }; 指针的用法如下: Rtm...

解决pycharm 误删掉项目文件的处理方法

解决pycharm 误删掉项目文件的处理方法

pycharm 文件丢了,怎么搞,不要慌, 鼠标右键点击想要恢复的项目,然后 local-history  show history  点击 revert ...

Python判断列表是否已排序的各种方法及其性能分析

声明 本文基于Python2.7语言,给出判断列表是否已排序的多种方法,并在作者的Windows XP主机(Pentium G630 2.7GHz主频2GB内存)上对比和分析其性能表现...

pytorch 转换矩阵的维数位置方法

例如: preds = to_numpy(preds)#preds是[2985x16x2] preds = preds.transpose(2, 1, 0)#preds[2x16x2...

在pycharm 中添加运行参数的操作方法

在pycharm 中添加运行参数的操作方法

最近又重新看手上的代码,之前弄不明白的地方这次要一次弄明白。 代码中出现了很多sys.arfv[]的运行参数,pycharm怎么添加运行参数呢 打开Run->Edit Config...