2

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'
3
  • 1
    You should call super() without arguments in python 3 Commented Nov 23, 2015 at 22:30
  • 1
    Or with the correct type - super( SubClass , self) Commented Nov 23, 2015 at 22:31
  • Thanks Sebastian for highlighting the distinction between Python2 and Python-3 usage of super(). Commented Nov 23, 2015 at 22:54

2 Answers 2

6

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..

Sign up to request clarification or add additional context in comments.

Comments

0

In the inheriting sub class (SubClass in ./sub_class.py), change this:

from super_class import SuperClass

class SubClass(SuperClass):

  def __init__(self):
     super(SuperClass, self).__init__()   # <---- INCORRECT. CHANGE THIS.
     self.varSub = 'varSub_value'

To this:

from super_class import SuperClass

class SubClass(SuperClass):

  def __init__(self):
     super(SubClass, self).__init__()   # <---- TO THIS in python-2 (also still valid in Python-3)
     super().__init__()                 # <---- OR THIS for python-3 (New style in python-3)
     self.varSub = 'varSub_value'

Btw, the python-3 new incantation avoids the possible bug of typing the wrong class.

Comments

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.