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

Why are f-strings not printed in Python class methods?

我想了解为什么 f 字符串不在 class 方法中打印输出。我想使用他们简洁的语法来制作断点。

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

这就是你方法中的打印内容 returns.

None

你看到这个是因为你正在打印你的 test() 方法 returning 的值,并且因为碰巧它 return 什么都没有(没有 return) 它给你这个 'None' 值。

yet this works

这正是 REPL 回显给您的内容。

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