You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Python类方法并用print输出时为何会出现None?

为什么Python中print包裹类方法调用会输出None?

嗨,我来给你把这个问题说透!你遇到的这个None,其实是Python函数/方法的默认返回值在搞鬼。

咱们先看你的代码里的方法,比如checkLife()和attack():它们都是直接在方法内部用print()输出内容,但完全没有写return语句。在Python里,任何没有显式返回值的函数/方法,默认都会返回None。

那你写print(e1.checkLife())的时候,其实发生了两件事:

  1. 先执行e1.checkLife(),这时候方法内部的print()会输出3 lives left...
  2. 然后print()函数会把e1.checkLife()的返回值(也就是默认的None)打印出来

这就是为啥你会看到输出内容后面跟着个None啦!

怎么解决这个问题?

有两种简单的处理方式:

  • 方式一:直接调用方法,不用print包裹
    比如把print(e1.checkLife())改成e1.checkLife(),这样就只会执行方法内部的print,不会额外打印返回值了。
  • 方式二:修改方法,让它返回字符串而非直接打印
    调整方法的逻辑,把输出的内容作为返回值,然后外层用print打印这个返回值,示例如下:
class Enemy:
    life = 3
    def attack(self):
        self.life -= 1
        return "ouch!"
    def checkLife(self):
        if self.life <= 0:
            return 'dead!'
        else:
            return f"{self.life} lives left..."

e1 = Enemy()
print(e1.checkLife())  # 只会输出 3 lives left...
print(e1.attack())     # 只会输出 ouch!
print(e1.checkLife())  # 只会输出 2 lives left...

这样修改后,方法会返回你想要的字符串,外层的print就只会打印这个返回值,不会出现None了。

内容的提问来源于stack exchange,提问作者user9141560

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:32:23