Skip to main content
 首页 » 编程设计

python之我有一个子类继承自父类(super class)并覆盖一个函数。如何让输出显示为 3 和 6

2025年05月04日13bonelee

我已经弄乱了参数和一般的类,但我仍然无法让它工作。即使我删除了我需要的 self.v3,我也会得到 None 作为第二个输出...

class Base(object): 
    def __init__(self, v1, v2): 
        self.v1 = v1 
        self.v2 = v2 
    def together(self): 
        return self.v1 + self.v2 
 
class Sub1(Base): 
    def __init__(self, v1, v2, v3): 
        super(Sub1, self).__init__(v1, v2) 
        self.v3 = v3 
    def together(self): 
        super(Sub1, self).together() + self.v3 
b1 = Base(1,2) 
print b1.together() 
s1 = Sub1(3,2,1) 
print s1.together() 

输出:3, 6

请您参考如下方法:

您的子类的together 方法实际上并不返回值。改成

return super(Sub1, self).together() + self.v3