[英]Python yield (migrating from Ruby): How can I write a function without arguments and only with yield to do prints?
我一直在将Ruby代码转换为Python代码,现在我坚持使用包含yield
函数:
def three_print():
yield
yield
yield
由于三个yield
语句,我想调用该函数并告诉它打印“Hello”三次。 由于函数不接受任何参数,我得到一个错误。 你能告诉我最简单的方法吗? 谢谢。
yield
在Ruby和yield
在Python是两个完全不同的事情。
在Ruby中, yield
运行一个块作为参数传递给函数。
红宝石:
def three
yield
yield
yield
end
three { puts 'hello '} # runs block (prints "hello") three times
在Python中, yield
从生成器抛出一个值(这是一个使用yield
的函数)并停止执行该函数。 所以它是完全不同的东西,更有可能你希望将函数作为参数传递给Python中的函数。
蟒蛇:
def three(func):
func()
func()
func()
three(lambda: print('hello')) # runs function (prints "hello") three times
Python生成器
下面的代码(您提供的代码)是一个返回None
三次的生成器:
def three():
yield
yield
yield
g = three() #=> <generator object three at 0x7fa3e31cb0a0>
next(g) #=> None
next(g) #=> None
next(g) #=> None
next(g) #=> StopIteration
我可以想象它是如何用于打印“Hello”三次的唯一方法 - 使用它作为迭代器:
for _ in three():
print('Hello')
Ruby类比
你可以使用Enumerator.new
在Ruby中做类似的事情:
def three
Enumerator.new do |e|
e.yield # or e << nil
e.yield # or e << nil
e.yield # or e << nil
end
end
g = three
g.next #=> nil
g.next #=> nil
g.next #=> nil
g.next #=> StopIteration
three.each do
puts 'Hello'
end
Python中的yield
不像Ruby那样有效。 特别是,它并不意味着“在这里执行块参数”。 此函数永远不会执行回调。
在Python中, yield
用于创建迭代器(特别是生成器),并且您发布的函数将返回一个生成None
3次的迭代器。 您可以遍历迭代器并为每个值打印“Hello”,忽略None
:
for _ in three_print():
print("Hello")
这是你最接近Ruby行为的,但在底层机制方面仍然存在根本的不同。
另外,如果你想将执行的回调3倍的功能,这将是
def f(callback):
callback()
callback()
callback()
你可以称之为
f(lambda: print("Hello"))
您可以使用 :
def three_print():
yield"Hello\n"*3
print(''.join(list(three_print())))
# Hello
# Hello
# Hello
你可以循环屈服:
def hello():
for i in range(3):
yield "hello"
print(list(hello()))
输出:
['hello', 'hello', 'hello']
在Python3.3及更高版本中,您可以使用yield from
语句:
def hello():
yield from ["hello" for i in range(3)]
print(list(hello()))
输出:
['hello', 'hello', 'hello']
def three_print():
yield("Hello")
yield("Hello")
yield("Hello")
因为有三个yields
,你需要调用three_print().next()
三次以获得"Hello"
字符串输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.