0

I have a BaseClass and an AbstractClass that inherits from the BaseClass. This is the structure I have in place

class BaseClass(object):
 def __init__(self, initialize=True):
 self.name = 'base_class'
 self.start = 0
 if initialize:
 self.start = 100
class AbstractClass(BaseClass):
 def __init__(self):
 self.name = 'asbtract_class'
 super(BaseClass, self).__init__()

I want to pass the abstract class an initialize parameter that gets transferred to the base class and if True sets the object's start value to 100.

I tried using the super(BaseClass, self).__init__() but the abstract class gets no start attribute. I get an error when I try to access it.

How can I pass a value the initialize argument to the AbstractClass and use the BaseClass's __init__ method to set the start attribute on the AbstractClass.

The code I used

best = BaseClass()
abs = AbstractClass()
abs.start # AttributeError: 'AbstractClass' object has no attribute 'start'
asked Jun 22, 2018 at 8:57
2
  • 4
    If you are using Python3, you can simplify it to super().__init__() Commented Jun 22, 2018 at 9:03
  • @Sraw It works, thanks! Commented Jun 22, 2018 at 9:08

1 Answer 1

2

To invoke the constructor of the super class you should use the class name of the sub class and not the super class, i.e.:

class AbstractClass(BaseClass):
 def __init__(self):
 super(AbstractClass, self).__init__()
 self.name = 'abstract_class'

Note also that I changed the order of invoking the constructor of the super class and setting the name attribute. If you set it before calling the super, the attribute would be overridden by the constructor of the super class, which is most likely not what you intended

And as @Sraw pointed out, for python 3 the notation of calling the super no longer requires the referencing of the class name and can be simplified to

class AbstractClass(BaseClass):
 def __init__(self):
 super().__init__()
answered Jun 22, 2018 at 9:01
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this. I can access the start param now. But I also need to be able to pass the initialize argument from the AbstractClass . I mean something like this: abs = AbstractClass(initialize=False). Is there a way of doing that? Currently, this throws an error.
Just add the param to AbstractClass.__init__ and pass it when doing the super().__init__() call. No magic involved here, it's just plain ordinary boring function calls...
@brunodesthuilliers okay, got it working now. Thanks

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.