永恒的蓝色梦想 发表于 2020-3-25 18:57:02

Python iter() 函数

本帖最后由 永恒的蓝色梦想 于 2020-3-25 19:33 编辑

Python iter() 函数

语法iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

参数

当传入一个参数时,这个参数应该是一个可迭代对象

当传入两个参数时,第一个参数应该是一个 callable 对象,第二个对象可以是任意值

描述

当传入一个参数时,iter() 将会返回 iterable 的迭代器。

当传入两个参数时,iter() 将不断调用callable,直到它返回sentinel。

返回值

一个迭代器

例子

>>> list(iter(input,''))
u
fas
fdas
fdsa
gwj
jtehdg
gtw

['u', 'fas', 'fdas ', 'fdsa ', 'gwj', ' jtehdg', 'gtw']
>>> iter()
<list_iterator object at 0x0000018A8DF9BD90>
>>> list(_)

永恒的蓝色梦想 发表于 2020-3-25 18:57:59

本帖最后由 永恒的蓝色梦想 于 2020-4-10 18:20 编辑

一种可能的实现class iter:
    def __new__(cls,a,b=_no_arg,/):
      if b is _no_arg:
            if hasattr(a,'__iter__'):
                temp=a.__iter__()
            
            else:
                raise TypeError(f"'{a.__class__.__name__}' object is not iterable")

            if hasattr(temp,'__next__'):
                return temp

            else:
                raise TypeError(f"iter() returned non-iterator of type '{temp.__class__.__name__}'")

      else:
            return object.__new__(cls)

    def __init__(self,callable,sentinel,/):
      if hasattr(callable,'__call__'):
            self.__a=callable
            self.__b=sentinel
            self.__c=False
            
      else:
            raise TypeError("iter(v, w): v must be callable")
   
    def __iter__(self,/):
      return self
   
    def __next__(self):
      if self.__c:
            raise StopIteration

      temp=self.__a()

      if temp==self.__b:
            self.__c=True
            raise StopIteration

      else:
            return temp

    def __reduce__(self):
      if self.__c:
            return self.__class__,((),)
      else:
            return self.__class__,(self.__a,self.__b)

一个账号 发表于 2020-3-25 19:27:17

我写过了,只是忘记加入淘专辑了:https://fishc.com.cn/thread-161609-1-1.html

永恒的蓝色梦想 发表于 2020-3-25 19:47:04

一个账号 发表于 2020-3-25 19:46
以我的为准

Fa♂U{:10_255:}

zltzlt 发表于 2020-3-25 20:09:59

永恒的蓝色梦想 发表于 2020-3-25 18:57
一种可能的实现

弱弱地问一句,为什么要重写 __reduce__ 方法{:10_245:}

永恒的蓝色梦想 发表于 2020-3-25 20:18:54

zltzlt 发表于 2020-3-25 20:09
弱弱地问一句,为什么要重写 __reduce__ 方法

我也不知道为什么,但是 callable_iterator 对象重写了这个方法。
因为我的代码用 iter 对象来迭代,所以我把 __reduce__ 重写在了 iter 里{:10_248:}
页: [1]
查看完整版本: Python iter() 函数