1

class Parent:
    def __init__(self, name):
        self.name = name

    def printName(self):
        print(self.name)


class Child(Parent):
    def __init__(self, name):
        Parent.__init__(name)

bob = Child('Bob')
bob.printName()

It's working with super().__init__(name) but not with the class name, why?

ruohola
  • 21,987
  • 6
  • 62
  • 97
Aashif Ali
  • 53
  • 4

3 Answers3

2

It doesn't work since Parent.__init__ is defined to take two arguments: self and name, and you're passing just a single argument to it. Thus, if you want to call it like that, you need to use Parent.__init__(self, name). But there really is no point, and you should instead just use super().__init__(name), as you already know.

ruohola
  • 21,987
  • 6
  • 62
  • 97
0

The init() method always requires the self parameter, which is a reference to the object itself. Without the self parameter, the init() method would not have access to the object's attributes and would not be able to initialize them properly. The fix can be found here.

class Parent:
    def __init__(self, name):
        self.name = name

    def printName(self):
        print(self.name)


class Child(Parent):
    def __init__(self, name):
        Parent.__init__(self, name)

bob = Child('Bob')
bob.printName()
kibromhft
  • 911
  • 1
  • 7
  • 18
0

That is because Parent.__init__() always requires self.

However, super().__init__() does not require self because it implicitly finds the self by MRO (Method Resolution Order). You can see the order using Class.__mro__, as follows:

class Parent:
    def __init__(self, name):
        self.name = name

    def printName(self):
        print(self.name)


class Child(Parent):
    def __init__(self, name):
        Parent.__init__(self, name)

bob = Child('Bob')
print(Child.__mro__)
# (<class '__main__.Child'>, <class '__main__.Parent'>, <class 'object'>)

Here, if you use super.__init__(name) instead of Parent.__init(self, name), it will find Parent by the order.

For more information: see https://docs.python.org/3/library/functions.html#super

Park
  • 2,446
  • 1
  • 16
  • 25