gpt4 book ai didi

python - 发电机是可调用的吗?哪个是发电机?

转载 作者:太空狗 更新时间:2023-10-29 17:46:42 24 4
gpt4 key购买 nike

A generator is simply a function which returns an object on which you can call next, such that for every call it returns some value, until it raises a StopIteration exception, signaling that all values have been generated. Such an object is called an iterator.

>>> def myGen(n):
... yield n
... yield n + 1
...
>>> g = myGen(6)

我引用自 Understanding Generators in Python?

这是我想弄清楚的:

  1. 哪个是生成器? myGenmyGen(6)

    根据上面的引述,我认为生成器应该是myGen .和 myGen(6)是返回的迭代器对象。但我真的不确定。

  2. 当我尝试这样做时:

    >>> type(myGen)
    <type 'function'>
    >>> type(g) # <1>this is confusing me.
    <type 'generator'>
    >>> callable(g) # <2> g is not callable.
    False
    >>> callable(myGen)
    True
    >>> g is iter(g) # <3> so g should an iterable and an iterator
    True # at the same time. And it will be passed as an argument
    >>> for i in g: # to built-in function `next()` in a "for...in..." loop.
    print i # (is that correct?)

    6
    7

因此,根据 <1><2> , g的类型是“发电机”,它是不可调用的。但是generators are callable, and calling a generator gets you an iterator object这是怎么回事?

当我在寻找答案时,我遇到了 Every time you define a function python creates a callable object.

那么,我可以这样说吗? 当函数 myGen已定义,myGen是一个引用可调用对象的名称,该对象是具有 __call__ 的类的实例方法。在这种情况下,myGen是一个发电机,myGen(6)myGen 时返回的迭代器叫做。

但为什么 type(g)返回 <type 'generator'>在所有?这返回了 iterator因为没有return,我觉得这件事也很可疑函数中的语句。

不就是Functions always return something (at least None , when no return-statement was reached during execution and the end of the function is reached)吗?

最佳答案

不幸的是,术语令人困惑,因为“生成器”经常用于指代函数或返回的迭代器,以至于很难说哪一种用法更正确。 documentation of the yield statement

The yield statement is only used when defining a generator function, and is only used in the body of the generator function. Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a generator iterator, or more commonly, a generator.

original PEP introducing the concept

Note that when the intent is clear from context, the unqualified name "generator" may be used to refer either to a generator-function or a generator-iterator.

如果要明确区分,函数用“generator function”,迭代器用“generator iterator”。

关于python - 发电机是可调用的吗?哪个是发电机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21982118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com