为什么在Python类方法中不打印f字符串?

问题描述

我想了解为什么f字符串不能在类方法中打印输出。我想使用它们的简洁语法来创建断点。

MWE:

class FStringTest:
    def test(self):
        print('why does this work')
        f'but not this'

print(FStringTest().test())
f'yet this works'

输出:

why does this work
None
yet this works

解决方法

您是在Jupyter还是交互式python shell中运行它? 因为如果您是的话,那么REPL中的'P'代表打印(R = READ,E = EVALUATE,P = PRINT,L = LOOP),它将自动为您打印yet this works,而无需您明确调用打印功能。

所以:

why does this work

这是方法内部的打印结果返回。

None

之所以会看到此信息,是因为您正在打印test()方法返回的值,并且由于它碰巧不返回任何内容(不返回),因此会为您提供“无”值。

yet this works

这正是REPL回响给您的。

注意:将其另存为python脚本(.py),并尝试在VSC之类的IDE中运行,或尝试使用py <script_name>.py通过命令行运行,它不会向您显示最后一行输出。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...