Reputation: 183
I don't understand why the code uses the print_me method from Class D, and not the method in class A.
I did some testing using print-statements and can see that it reads the print_me-method of class D before initialising class A, but I don't understand why it doesn't do the same for class A.
class A:
name = "Alfa"
def __init__(self, foo):
self.foo = foo
foo = 100
self.print_me()
def print_me(self):
print(self.name, self.foo)
class B(A):
name = "Beta"
def __init__(self, bar = 40):
self.bar = bar
print(self.name, bar)
class C:
name = "Charlie"
class D(A, C):
name = "Delta"
def __init__(self, val):
A.__init__(self, val)
def print_me(self):
print(self.name, "says", self.foo)
d = D(60)
The output is: Delta says 60
I thought it would be: Delta 60
Upvotes: 0
Views: 110
Reputation: 29089
Because the self
you are passing to the __init__
of A
is still an instance of D
, not A
. And the function A.__init__
is calling self.print_me
, which belongs to D
.
If you do a = A(); a.print_me()
you'd get what you expect.
Important note: The __init__
method in python is not the actual constructor, it is just a method that is automatically called after the actual construction of the object. However, when you call it yourself, it works just like any other method.
Upvotes: 3