当我调用两个方法时,一个来自父类,一个来自子类,只有第一个调用返回

When I call two methods, one from the parent class and one from the child class, only the first call returns

提问人:Thiago 提问时间:10/28/2022 最后编辑:Thiago 更新时间:10/28/2022 访问量:23

问:

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'

如果我交换调用顺序,输出将是“测试父类”。

为什么会这样?

Python 对象 方法 调用

评论

0赞 juanpa.arrivillaga 10/28/2022
它们都返回,您不会对任何一个返回值执行任何操作。输出不是此脚本的输出,此脚本不输出任何内容。这看起来像您正在 Jupyter 笔记本或 IPython REPL 之类的东西中运行它,它将打印最后一个值,否则,您不应该期望打印任何内容
0赞 Thiago 10/28/2022
明白了。我正在使用 Jupyter 笔记本,我不知道它只打印最后一个值。谢谢!

答:

2赞 Tim Roberts 10/28/2022 #1

您没有打印任何东西。无论您使用什么 UI,都只是向您显示脚本生成的最后一个值。以正确的方式做:

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