1
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?

1
  • 4
    Firstly call constructor of super() to initialize class instance, then access to instance variable. Commented Aug 19, 2021 at 21:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

12 Comments

Also if you are working with Python 3, class Base should explicitely inherit object
You've got that backwards. If you're using Python 2 then it should inherit from object. In Python 3 it's not needed.
I think PEP says that though it's not required it's a good practice, I will give a look to this.
@May.D - Python 2 classes did not inherit from object originally. That was introduced when class semantics changed from "old style" to "new style" classes, and was something of a dirty hack. Since python 3, all classes are "new style" classes and the dirty hack isn't needed. Its really only there for backwards compatibility. This is one of those cases where I don't think that explicit wins.
@tomasz - that's a good point. An example is explicitly stating default arguments. open("whatever", "r") for instance subtly makes a reviewer think twice...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.