I have the following code:
class A(object):
def __init__(self):
self.name = "A"
super(A, self).__init__()
def Update(self):
print "Update A"
self.PickTarget()
def PickTarget(self):
print "PickTarget A"
class B(object):
def __init__(self):
self.name = "B"
super(B, self).__init__()
def Update(self):
print "Update B"
self.PickTarget()
def PickTarget(self):
print "PickTarget B"
class C(A, B):
def __init__(self):
super(C, self).__init__()
def Update(self, useA):
if useA:
A.Update(self)
else:
B.Update(self)
c = C()
c.Update(useA = True)
# prints:
# Update A
# PickTarget A
c.Update(useA = False)
# prints:
# Update B
# PickTarget A
Why does calling C.Update with useA=False still call into A.PickTarget? How can I make this work how I want it to work (ie B.Update always calls into B.PickTarget)? I’m sure this has been asked before but my searching turned up nothing – probably because I don’t know what to search for.
It’s because
Ais beforeBinC‘s base classes.You need to use
B.PickTarget(self)rather thanself.PickTarget()inB.Update(self)to get this behavior. Otherwise, switchAandBinC‘s definition.Edit:
If the intended behavior is for
Bto always call methods inBand forAto always call methods inA, it’s correct to useA.method(self)instead ofself.method(), as the second form doesn’t imply thatmethodis inA.You should redesign your classes.
Ashould have a move method that moves the robot randomly and define it’s other basic behavior.Bshould be a subclass ofAand should have a move method that callssuper(B, self).move()if it doesn’t have a path, and otherwise moves on the path. This is the proper way to override a method on a condition.