John Fabiani wrote:
Hi,
I want to create a class that inherits two other classes.
class NewClass( A,B)
But both "A" and "B" contain a method with the same name ("onKeyDown").
If my "NewClass" does not contain something to override the methods which one
would be called if
myinstance = NewClass()
myinstance.onKeyDown()
This depends on whether classes A and B are designed for cooperative multiple
inheritance or not.
The short answer is, A.onKeyDown will be called, because A is listed first.
The longer answer is, if A.onKeyDown uses super() to manager multiple
inheritance, both A and B.onKeyDown may be called.
Here is an example with no cooperative multiple inheritance:
class A(object):
def onKeyDown(self):
print('A deals with keydown event')
class B(object):
def onKeyDown(self):
print('B deals with keydown event')
class NewClass(A, B):
pass
And in use, you will see that A blocks B:
py> instance = NewClass()
py> instance.onKeyDown()
A deals with keydown event
And here is a second example using super() for cooperative multiple inheritance:
class A(object):
def onKeyDown(self):
print('A deals with keydown event')
super(A, self).onKeyDown()
# in Python 3, you can just use "super().onKeyDown()"
class B(object):
def onKeyDown(self):
print('B deals with keydown event')
# B does not call super(), because there are no
# further parent classes to call.
class NewClass(A, B):
pass
And in use:
py> instance = NewClass()
py> instance.onKeyDown()
A deals with keydown event
B deals with keydown event
Second to insure the right one is called is it possible to do the following
NewClass(object):
def onKeyDown(self, event):
b.onKeyDown(event)
Yes, but that normally should not be necessary if you design your classes
carefully.
--
Steven
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor