0

In the code:

class Mother(object):
    def __init__(self):
        self._haircolor = "Brown"

class Child(Mother):
    def __init__(self): 
        #Mother.__init__(self)
        super(Mother, self).__init__(self)

    def print_haircolor(self):
        print self._haircolor

c = Child()
c.print_haircolor()

Why does Mother.__init__(self) work fine (it outputs Brown), but super(Mother, self).__init__(self) give the error

Traceback (most recent call last):
  File "test2.py", line 13, in <module>
    c = Child()
  File "test2.py", line 8, in __init__
    super(Mother, self).__init__(self)
TypeError: object.__init__() takes no parameters

I've seen this, this, this and this, but it doesn't answer the question.

2
  • 3
    From the docs, The super object is bound to its second argument - so I imagine that under the hoods it is passing self to the method and you do not need to pass it again.
    – wwii
    Apr 13, 2019 at 13:43
  • 1
    If possible, you should switch to Python 3. pythonclock.org
    – wwii
    Apr 13, 2019 at 13:45

1 Answer 1

4

You have two related issues.

First, as the error states, object.__init__() takes no arguments, but by running super(Mother, self).__init__(self), you're trying to pass in an instance of Child to the constructor of object. Just run super(Mother, self).__init__().

But second and more importantly, you're not using super correctly. If you want to run the constructor of the Mother class in Child, you need to pass in the subclass Child, not the superclass Mother. Thus, what you want is super(Child, self).__init__(self).

When these fixes are added to your code, it runs as expected:

class Mother(object):
    def __init__(self):
        self.haircolor = "Brown"

class Child(Mother):
    def __init__(self): 
        super(Child, self).__init__()

    def print_haircolor(self):
        print self.haircolor

c = Child()
c.print_haircolor() # output: brown

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.