Search code examples
pythoninheritancesubclasssuperclass

Python :: Attribute in superclass not available in inheriting subclass


I'm wondering why the below fails; basically that an inheriting subclass (SubClass) doesn't appear to have access to an attribute in the superclass (SuperClass) that it inherits from.

By the way, all three files below are in the same directory and, for completeness, I'm using Python3.

Any ideas? I think it's something stunningly simple. Thank you!

The super class (SuperClass in ./super_class.py) ...

class SuperClass(object):

   def __init__(self):
      self.varSuper = 'varSuper_value'

The inheriting sub class (SubClass in ./sub_class.py) ...

from super_class import SuperClass

class SubClass(SuperClass):

  def __init__(self):
     super(SuperClass, self).__init__()
     self.varSub = 'varSub_value'

The driver/tester script (./driver.py) ...

#! /usr/bin/env python3

from sub_class import SubClass

print(SubClass().varSub)    # Works: "varSub_value"
print(SubClass().varSuper)  # Excepts: I expected "varSuper_value"

The exception ...

user@linux$ ./driver.py
varSub_value                                  <--- GOOD
Traceback (most recent call last):
  File "./driver.py", line 6, in <module>
    print(SubClass().varSuper)                <--- NO GOOD
AttributeError: 'SubClass' object has no attribute 'varSuper'

Solution

  • You are using the super() function wrong. You should be using:

    super(SubClass, self).__init__()
    

    Or in python3

    super().__init__()
    

    The way you have it written you are starting the MRO just after the parent class, not just after your own class..