Bigboss01
Bigboss01

Reputation: 618

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)

Hello, I'm learning about inheritance and super(). When running this, the error AttributeError: 'inherit' object has no attribute 'var' is returned. How can I inherit the init variables too?

Upvotes: 1

Views: 666

Answers (1)

May.D
May.D

Reputation: 1910

You first need to call super constructor because you did not define var in your base class constructor.

Working version of your code (though you should probably add var in base __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)

one possible solution

    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

Upvotes: 2

Related Questions