[英]Will the function in python for loop be executed multiple times?
假设我有一个返回列表的方法的以下类:
Class C():
def f():
return [1,2,3]
如果我循环这个方法如下:
c=C()
for i in c.f():
print i
在for循环中,cf()会被执行多次吗? 如果是,为了得到它一次,我是否必须在循环之外做任务,或者有一些微不足道的方法?
In [395]: def tester():
...: print "Tester Called!"
...: return [1,2,3]
In [396]: for i in tester():
...: pass
Tester Called!
似乎答案是否定的。
cf()
不会多次执行。
你没有问,但你可能对发电机很好奇。
您作为生成器的示例如下:
Class C():
def f():
yield 1
yield 2
yield 3
迭代结果的循环将保持不变。
来自python文档 :
for语句用于迭代序列的元素(例如字符串,元组或列表)或其他可迭代对象:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]
表达式列表评估一次 ; 它应该产生一个可迭代的对象。
不,它被执行一次 。
并且您的方法未正确定义。 应该有一个self
论点:
class C:
def f(self):
return [1,2,3]
它只会被执行一次。 但是代码中会出现语法错误:
class
,而不是上课
def f(self)
,而不是def f()
你有没有尝试自己测试一下? 你的问题的答案是否定的。
这是你应该如何测试它。 此外,您的代码中存在许多缺陷。 检查下面的自评注修改版本
>>> class C: #its class not Class and C not C()
def f(self): #You were missing the self argument
print "in f" #Simple Test to validate your query
return [1,2,3]
>>> c=C()
>>> for i in c.f():
print i
in f
1
2
3
>>>
虽然这个例子很简单,但我仍然会以此为例来解释我们如何利用Python 函数式编程的强大功能 。 我将尝试解释的是懒惰评估或生成器函数(http://docs.python.org/glossary.html#term-generator)。
考虑修改后的例子
>>> class C: #its class not Class and C not C()
def f(self): #You were missing the self argument
print "in f" #Simple Test to validate your query
for i in [1,2,3]:
yield i #Generates the next value when ever it is requsted
return #Exits the Generator
>>> c=C()
>>> for i in c.f():
print i
in f
1
2
3
>>>
您看得出来差别吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.