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面相对象编程中对象的属性与类的方法

python 对象的属性 进入正题,来看一个实例来了解python中类,对象中公有属性,私有属性及局部变量,全局变量的区别. root@10.1.6.200:~# cat objec...

python实现12306登录并保存cookie的方法示例

经过倒腾12306的登录,还是实现了,请求头很重要...各位感兴趣的可以继续写下去..... import sys import time import requests from...

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...

3种python调用其他脚本的方法

1.用python调用python脚本 #!/usr/local/bin/python3.7 import time import os count = 0 str = ('pyt...

python2与python3中关于对NaN类型数据的判断和转换方法

python2与python3中关于对NaN类型数据的判断和转换方法

今天在对一堆新数据进行数据清洗的时候,遇到了一个这样的问题: ValueError: cannot convert float NaN to integer 一开始是这样的,我用...