0

I have a question about a program:

class A:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def to_string(self):
        return "x, y = (" + str(self.x) + ", " + str(self.y) + ")"

    def __str__(self):
        return self.to_string()


class B(A):
    def __init__(self, z, *args):
        A.__init__(self, *args)
        self.z = z

    def __str__(self):
        return super().__str__()


class C(A):
    def __init__(self, *args):
        super().__init__(*args)

    def to_string(self):
        return "Klasse C, " + super().to_string()

Why I have to write

A.__init__(self, *args)

instead of

A.__init__(*args)

In class C it works? Lots of greetings

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Fleksiu
  • 191
  • 1
  • 10

1 Answers1

4

You are accessing the unbound method, so self is not passed in. There is no context for A.__init__ to know what instance to bind to.

You have several options to provide that context:

  • Pass in self explicitly, as you did.
  • Bind manually, with A.__init__.__get__(self)(*args)
  • In Python 3, use super().__init__(*args) and the context is then taken from the current method. See Why is Python 3.x's super() magic?
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343