Python产量与Ruby产量 [英] Python yield vs Ruby yield

查看:105
本文介绍了Python产量与Ruby产量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,yield关键字用于屈服于执行块的闭包.

In Ruby, the yield keyword is used to yield to closures for blocks of execution.

此关键字在Python语言中有何不同?

How does this keyword differ in the Python language?

推荐答案

在ruby 中,yield是用于调用匿名函数的快捷方式. Ruby具有用于将匿名函数传递给方法的特殊语法.该语法称为block.由于该函数没有名称,因此可以使用名称​​ yield 来调用该函数:

In ruby, yield is a shortcut that is used to call an anonymous function. Ruby has a special syntax for passing an anonymous function to a method; the syntax is known as a block. Because the function has no name, you use the name yield to call the function:

def do_stuff(val)
  puts "Started executing do_stuff"
  yield(val+3)
  yield(val+4) 
  puts "Finshed executing do_stuff" 
end

do_stuff(10) {|x| puts x+3} #<= This is a block, which is an anonymous function
                            #that is passed as an additional argument to the 
                            #method do_stuff

--output:--
Started executing do_stuff
16
17
Finshed executing do_stuff

在python 中,当您在函数定义中看到yield时,表示该函数是generator.生成器是一种特殊的功能,可以在执行过程中停止并重新启动.这是一个示例:

In python, when you see yield inside a function definition, that means that the function is a generator. A generator is a special type of function that can be stopped mid execution and restarted. Here's an example:

def do_stuff(val):
    print("Started execution of do_stuff()")

    yield val + 3
    print("Line after 'yield val + 3'")
    yield val + 4
    print("Line after 'yield val + 4'")

    print("Finished executing do_stuff()")


my_gen = do_stuff(10)

val = next(my_gen)    
print("--received {} from generator".format(val))

输出:

Started execution of do_stuff()
--received 13 from generator

更多代码:

val = next(my_gen)    
print("--received {} from generator".format(val))

输出:

Line after 'yield val + 3'
--received 14 from generator

从输出中,您可以看到yield导致返回结果;然后立即停止执行.当您再次在生成器上调用next()时,执行将继续,直到遇到下一个yield语句为止,该声明将返回一个值,然后再次停止执行.

From the output, you can see that yield causes a result to be returned; then execution is immediately halted. When you call next() again on the generator, execution continues until the next yield statement is encountered, which returns a value, then execution halts again.

这篇关于Python产量与Ruby产量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆