Consider Python multiple inheritance:
class A(object):
def __init__(self):
self.name = 'a'
def y(self):
return "A"
class B(A):
def __init__(self):
A.__init__(self)
self.name = 'b'
def y(self):
return "B"
class C(object):
def __init__(self):
self.name = 'c'
def y(self):
return "C"
class D(C, B):
def __init__(self):
C.__init__(self)
B.__init__(self)
When creating an instance of D
it can be seen that as Python goes through each constructor it reassigns self.name
and therefore the value of self.name
is, as expected, the last value assigned to it:
>>> foo = D()
>>> print(foo.name)
b
However, for the method y()
it seems that the method assigned is the first method assigned to it:
>>> print(foo.y())
C
Why the discrepancy between which attributes are assigned? What are the rules? The Python manual in fact has a section on multiple inheritance, however I don't see this topic mentioned there.
Note that this question is not homework, but it is adapted from a lesson in the wonderful Introduction to Computer Science and Programming Using Python course.