首页 > 解决方案 > 使用 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'返回错误。我怎样才能继承初始化变量呢?

标签: pythonoopinheritancesuper

解决方案


您首先需要调用super构造函数,因为您没有varbase类构造函数中定义。

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

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

推荐阅读