Python yield(从 Ruby 迁移):如何编写不带参数且仅使用 yield 进行打印的函数?

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

我想调用该函数并告诉它打印 "Hello" 三次,因为有三个 yield 语句。由于该函数不接受任何参数,因此出现错误。你能告诉我让它工作的最简单方法吗?谢谢。

你可以循环 yield:

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

因为有3个yields,需要调用3次three_print().next()才能得到"Hello"字符串输出

Python 中的

yield 与 Ruby 中的不同。特别是,它并不意味着 "execute the block argument here"。此函数永远不会执行回调。

在 Python 中,yield 用于创建迭代器(特别是生成器),您发布的函数将 return 一个生成 None 3 次的迭代器.您可以遍历迭代器并为每个值打印 "Hello",忽略 None:

for _ in three_print():
    print("Hello")

这是您最接近 Ruby 行为的方式,但在基础机制方面仍然存在根本差异。

或者,如果您想要一个将执行回调 3 次的函数,那就是

def f(callback):
    callback()
    callback()
    callback()

你可以称它为

f(lambda: print("Hello"))
Ruby中的

yield和Python中的yield是两个截然不同的东西。

在 Ruby yield 中运行作为参数传递给函数的块。

Ruby:

def three
  yield
  yield
  yield
end

three { puts 'hello '} # runs block (prints "hello") three times

In Python yield 从生成器(这是一个使用 yield 的函数)中抛出一个值并停止执行该函数。所以这是完全不同的东西,你更有可能想将一个函数作为参数传递给 Python.

中的函数

Python:

def three(func):
  func()
  func()
  func()

three(lambda: print('hello')) # runs function (prints "hello") three times

Python 发电机

下面的代码(您提供的代码)是一个 returns 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类比

您可以在 Ruby 使用 Enumerator.new:

做类似的事情
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

您可以使用:

def three_print():
  yield"Hello\n"*3
print(''.join(list(three_print())))

# Hello
# Hello
# Hello