我正在尝试编写一个程序来简化一首经典的饮酒歌曲,而 Python 解释器的行为非常奇怪。
我的代码是这样的:
def lines():
bottles = 99
while bottles > 0:
yield str(bottles) + ' bottles of pop on the wall!'
yield str(bottles) + ' bottles of pop!'
yield 'Take one down and pass it around!'
bottles -= 1
yield str(bottles) + ' bottles of pop on the wall!'
yield ''
def sing():
for line in lines():
print(line)
这按预期从 Linux 命令行运行;它可能会打印“1 瓶汽水”,但它现在可以满足我的要求。
但是,从 JetBrains 中的“Python 控制台”,我得到了一些排列:
>>> ninetynine.sing()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\chris\PycharmProjects\untitled\ninetynine.py", line 10, in sing
for line in lines():
TypeError: 'function' object is not iterable
我试着用稍微不同的方式来调用它,结果:
>>> for line in ninetynine.lines():
... print(line)
99 bottles of pop on the wall!
99 bottles of pop!
Take one down and pass it around!
98 bottles of pop on the wall!
>>>
我还没有做到的是让它像一个循环运行的生成器一样工作。
我可以或应该做什么来从 PyCharm 获得正确的 REPL 行为?
--更新--
正在进行一些愚蠢的缓存。
我重新键入了 .py 文件,但输入了最后一个 yield statemest,
yield str(bottles + ' bottles of pop on the wall!')
这给出了明显的错误,所以我更改了源文件并保存:
yield str(bottles) + ' bottles of pop on the wall!
在我从 REPL 重新导入 bottles 后,它报告了完全相同的错误,只有它指向的行是我正确的 bottles.py 行,现在正确放置了 ) 紧跟在 bottles 之后。
所以有某种脏缓存在进行;我认为源代码无法重新编译或类似的问题。
是否有“make clean”选项,或者更好的是,如果源文件比编译后的形式更新,或者根本不保存字节码,将重新编译的设置?
请您参考如下方法:
您是在控制台中导入文件吗?
九十九.py:
def lines():
bottles = 99
while bottles > 0:
yield str(bottles) + ' bottles of pop on the wall!'
yield str(bottles) + ' bottles of pop!'
yield 'Take one down and pass it around!'
bottles -= 1
yield str(bottles) + ' bottles of pop on the wall!'
yield ''
def sing():
for line in lines():
print(line)
pycharm -> 工具 -> python 控制台...
>>> import ninetynine
>>> ninetynine.sing()
99 bottles of pop on the wall!
99 bottles of pop!
Take one down and pass it around!
98 bottles of pop on the wall!
98 bottles of pop on the wall!
98 bottles of pop!
Take one down and pass it around!
97 bottles of pop on the wall!
...
1 bottles of pop on the wall!
1 bottles of pop!
Take one down and pass it around!
0 bottles of pop on the wall!
对我来说很好。
