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

Python中调用父类与子类方法仅返回首个结果的原因解析

问题描述

以下是编写的Python代码:

class Smarthphone():
    def __init__(self, tamanho, interface):
        self.tamanho = tamanho
        self.interface = interface
        
    def print_test(self):
        return "testing parent class"

class MP3Player(Smarthphone):
    def __init__(self, tamanho, interface, capacidade):
        super().__init__(tamanho, interface)
        self.capacidade = capacidade
        
    def print_MP3Player(self):
        return f"tamanho:{self.tamanho} interface:{self.interface} capacidade:{self.capacidade}"
        
ob1 = MP3Player(5, 'led', '240GB')

ob1.print_test()
ob1.print_MP3Player()

输出结果为:

'tamanho:5 interface:led capacidade:240GB'

若调换方法调用顺序:

ob1.print_MP3Player()
ob1.print_test()

输出结果则为'testing parent class'。请问为何会出现该现象?

原因解释

这是因为你在**Python交互式环境(比如IDLE、终端Python shell或IPython)**中执行代码时,解释器只会自动打印最后一个表达式的返回值,前面的方法调用虽然正常执行,但它们的返回值没有被显式输出。

  • 当先调用ob1.print_test()再调用ob1.print_MP3Player()时,最后一行是ob1.print_MP3Player(),所以解释器会打印这个方法的返回值。
  • 调换顺序后,最后一行是ob1.print_test(),因此解释器只会打印这个方法的返回值。

如果想要同时看到两个方法的返回结果,需要用print()函数显式输出每个调用的结果,比如:

print(ob1.print_test())
print(ob1.print_MP3Player())

这样无论调用顺序如何,两个结果都会被打印出来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:25:26