简体   繁体   English

python for循环中的函数会被执行多次吗?

[英]Will the function in python for loop be executed multiple times?

Say I have the following class with a method returning a list: 假设我有一个返回列表的方法的以下类:

Class C():
  def f():
    return [1,2,3]

If I loop over the this method as follows: 如果我循环这个方法如下:

c=C()
for i in c.f():
  print i

Inside the for loop, will cf() be executed multiple times? 在for循环中,cf()会被执行多次吗? If yes, in order to get it once, do I have to do assignment outside of the loop, or there is some trivial way? 如果是,为了得到它一次,我是否必须在循环之外做任务,或者有一些微不足道的方法?

In [395]: def tester():
     ...:     print "Tester Called!"
     ...:     return [1,2,3]

In [396]: for i in tester():
     ...:     pass
Tester Called!

Seems the answer is no. 似乎答案是否定的。

cf() will not get executed multiple times. cf()不会多次执行。

You didn't ask, but you might be curious about generators . 你没有问,但你可能对发电机很好奇。

Your example as a generator would be as follows: 您作为生成器的示例如下:

Class C():
  def f():
    yield 1
    yield 2
    yield 3

The loop where you iterate over the results would be unchanged. 迭代结果的循环将保持不变。

from the python docs : 来自python文档

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: for语句用于迭代序列的元素(例如字符串,元组或列表)或其他可迭代对象:

 for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] 

The expression list is evaluated once ; 表达式列表评估一次 ; it should yield an iterable object. 它应该产生一个可迭代的对象。

No it is executed once . 不,它被执行一次

And your method is not correctly defined. 并且您的方法未正确定义。 Should have a self argument: 应该有一个self论点:

class C:
  def f(self):
    return [1,2,3]

It will be executed only once. 它只会被执行一次。 But there will be syntax errors in your code: 但是代码中会出现语法错误:

class , not Class class ,而不是上课
def f(self) , not def f() def f(self) ,而不是def f()

Did you try to test it yourself? 你有没有尝试自己测试一下? The answer to your question is NO. 你的问题的答案是否定的。

Here is how you should have tested it. 这是你应该如何测试它。 Moreover there were lot of flaws in your code. 此外,您的代码中存在许多缺陷。 Check the self commented modified version below 检查下面的自评注修改版本

>>> 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
>>> 

Though this example is trivial but still I will use this as an example to explain how we can leverage the power of functional programming of Python. 虽然这个例子很简单,但我仍然会以此为例来解释我们如何利用Python 函数式编程的强大功能 What I will try to explain is called lazy evaluation or generator functions(http://docs.python.org/glossary.html#term-generator). 我将尝试解释的是懒惰评估或生成器函数(http://docs.python.org/glossary.html#term-generator)。

Consider the modified example 考虑修改后的例子

>>> 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
>>> 

Can you spot the difference? 您看得出来差别吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM