使用 super() 从多个 class 函数继承变量

Inheriting variables from multiple class functions with super()

class base():
    def __init__(self):
        self.var = 10
        
    def add(self, num):
        res = self.var+num
        return res
    
class inherit(base):
    def __init__(self, num=10):
        x = super().add(num)

a = inherit()
print(a)

您好, 我正在学习继承和 super()。当运行这个时,返回错误AttributeError: 'inherit' object has no attribute 'var'。我怎样才能继承初始化变量?

您首先需要调用 super 构造函数,因为您没有在 base class 构造函数中定义 var

您代码的工作版本(尽管您可能应该在基础 __init__ 中添加 var)

class Base:
    def __init__(self):
        self.var = 10

    def add(self, num):
        res = self.var + num
        return res


class Inherit(Base):
    def __init__(self, num=10):
        super().__init__()
        x = super().add(num)


a = Inherit()
print(a)

一个可能的解决方案

    class Base:
        def __init__(self, var=10):
            self.var = var
    
        def add(self, num):
            res = self.var + num
            return res
    
    
    class Inherit(Base):
        pass


a = Inherit()
a.add(0)  # replace 0 with any integer