gpt4 book ai didi

类中的python生成器

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:22 25 4
gpt4 key购买 nike

我正在从这个 thread 学习生成器.这确实是生成器的一个很好的例子。但是我对其中一个示例代码感到困惑。

>>> class Bank(): # let's create a bank, building ATMs
... crisis = False
... def create_atm(self):
... while not self.crisis:
... yield "$100"
>>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>

>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>

>>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business
>>> for cash in brand_new_atm:
... print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...

hsbc.crisis 重置为 False 时,corner_steet_atm 只能产生 StopIteration。为什么会这样。我认为危机过后 corner_street_atm 并非空无一人。

最佳答案

问题出在当你说

corner_street_atm = hsbc.create_atm()

您只调用一次该函数,这就是它会被调用的所有次数。因此,让我们了解正在发生的事情

  def create_atm(self):
# Called right away, when you say the above line and only then
print("Called function")

# Loops while crisis = False
while not self.crisis:
yield "$100"

现在,我们可以问当危机为真时我们的方法在寻找什么,我们发现它指向下图所示的位置:

  def create_atm(self):
# Called right away, when you say the above line and only then
print("Called function")

# Loops while crisis = False
while not self.crisis:
yield "$100"
#<------ Where you function points after you set crisis to false and get the next

好吧,那里什么也没有,所以你得到一个错误。

您真正要查找的似乎是 atm 中的无限循环。像这样:

class Bank():
crisis = False

def create_atm(self):
print("Called function")
while True:
if not self.crisis:
yield "$100"
else:
yield "$0"

小心这个,作为你的最后决定

for cash in brand_new_atm:
print(cash)

将永远循环,因为您目前看不到自动取款机中有多少现金(因此只要没有危机,它就会喷出美元钞票。

关于类中的python生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37535857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com