0

Please take a look at the sample code below. The parent class, needs to call the setup() function, but that function needs to be defined/overwritten in the child class. But the sample code below shows that when child is initialized and called super(), the super's method calls the parent setup() which contains nothing.

Intended behavior is when child is instantiated, it calls parent's __init__ by using super() and automatically call the setup function defined in the child. Setting Human.setup() as abstract class also did not seem to work.

Google can only find information on how to call parent's method from child, but this case is the reverse, "How to call child's method from parent". Or is it not possible in python3?

The reason it needs to call the setup function of the child is due to each child class will be having a different setup procedure. But they share most of the methods defined in the parent class.

class Human(object):
    def __init__(self):
        self.setup()

    def setup(self):
        pass

class child(Human):
    def __init__(self):
        super()

    def setup(self):
        self.name = "test"

>>> A = child()
>>> A.name
    AttributeError: 'child' object has no attribute 'name'
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
thuyein
  • 1,684
  • 13
  • 29
  • 1
    Your child class constructor is broken. It never calls the parent class constructor. Change `super()` to `super().__init__()` and everything will work. – Aran-Fey Jul 25 '18 at 08:45

1 Answers1

0

You are not calling Human's __init__ from child's __init__.

super() gives you a handle through which to call superclass methods, but you need to do that via method calls on super().

In this case:

class Child(Human):
    def __init__(self):
        super().__init__()
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Oh I see. Thanks. I was reading python3 and python2 difference recently. https://stackoverflow.com/a/10483204/1509809 I used to do `super().__init__(self)` in python2 but mistaken that `super()` is not equivalent to `super().__init__()` in python3 – thuyein Jul 25 '18 at 09:03