[英]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.