1

according to inheritance in python, to override the constructor and at the same time implement it, you use something like this

class Dog :
    def __init__(self, name) :
        self.name = name 
        print("This is a dog named {}".format(self.name))

class Bingo(Dog) :
    def __init__(self, name) :
        super().__init__(self.name)

But I notice in some code I came across, super itself carry argument like,

    super(self, name).__init__()

so if I may ask, where is the argument passed to, is it the parent class or what. I find it hard to wrap my head on this, I actually encountered it on code in PyQt and PySide

PersianGulf
  • 2,845
  • 6
  • 47
  • 67
Temitayo
  • 802
  • 2
  • 12
  • 28
  • 1
    `super()` is most likely from `Python 3.x` code, where arguments are optional. In `Python 2.x`, you had to write `super(,)` to get the same effect. But in both cases, you pass the arguments to the `___init__` to the constructor itself (i.e. `__init__()`). – isedev Feb 27 '14 at 14:00
  • possible duplicate of [Why is Python 3.x's super() magic?](http://stackoverflow.com/questions/19608134/why-is-python-3-xs-super-magic) – Martijn Pieters Feb 27 '14 at 14:01
  • 1
    `self` and `name` are arguments to the `super()` object, and are actually the wrong arguments to pass in. The first argument must be a type (so the class), the second must be an instance of the first argument. – Martijn Pieters Feb 27 '14 at 14:04
  • note: `super().__init__(self.name)` in your code is wrong anyway, since the object does not have a `name` attribute when that line is called (since the attribute is created in `Dog.__init__` which hasn't been called yet). – isedev Feb 27 '14 at 14:04
  • I realize that the duplicate I linked you to is rather technical, but it does spell out the reasons for why there is a `super()` form, and why it exists compared to the `super(ClassObject, self)` form. – Martijn Pieters Feb 27 '14 at 14:06
  • Thanks all, now I get it – Temitayo Feb 27 '14 at 14:30

1 Answers1

0

In Python 2.x you would have had to write

class Bingo(Dog) :
    def __init__(self, name) :
        super(Dog, self).__init__(name)

because super required the superclass name (Dog) and the instance (self). The super's __init__ is Dog.__init__ so would typically come from Bingo.__init__ args (such as name), not as you had it (self.name, incorrect since doesn't exist yet).

In Python 3.0 you can write

class Bingo(Dog) :
    def __init__(self, name) :
        super().__init__(name)

because super() was given extra behavior that allows it to figure out Dog and self for you.

Oliver
  • 27,510
  • 9
  • 72
  • 103