Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python如何知道何时返回生成器?_Python_Generator - Fatal编程技术网

python如何知道何时返回生成器?

python如何知道何时返回生成器?,python,generator,Python,Generator,显然,当我在函数体中放入一个yield时。但这不是我想问的。给出了交互式解释器中的两个简单函数: def myGenerator(): yield 42 def myFunction(): return 42 当我执行这两个命令时,我看到: >>> myGenerator() <generator object myGenerator at 0xb7bf511c> >>> myFunction() 42 生成与myGenera

显然,当我在函数体中放入一个
yield
时。但这不是我想问的。给出了交互式解释器中的两个简单函数:

def myGenerator():
    yield 42

def myFunction():
    return 42
当我执行这两个命令时,我看到:

>>> myGenerator()
<generator object myGenerator at 0xb7bf511c>
>>> myFunction()
42
生成与myGenerator相同的内容。在函数对象的内部是否隐藏了一些神奇的东西,解释器从中分支出来,以辨别是否将函数调用包装为生成器?或者它是以装饰风格完成的,其中yield关键字的存在导致绑定为
'myGenerator'
的对象被包装成某种生成器魔法?“生成器函数在所有方面都是普通函数对象,但在代码对象的CO_标志成员中设置了新的CO_生成器标志。”

来自政治公众人物

请回答:
for attr in dir(myFunction):
    print(attr, getattr(myFunction, attr)
 >>> generator_fn.__code__.co_flags
 >>> 99
 >>> normal_fn.__code__.co_flags
 >>> 67