我有以下代码:
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
为什么调用C.Update
with useA=False
仍然呼入A.PickTarget
?我怎样才能让它按照我想要的方式工作(即B.Update总是调用B.PickTarget)?我确信以前有人问过这个问题,但我的搜索没有结果 - 可能是因为我不知道要搜索什么。
这是因为A
是在之前B
in C
的基类。
你需要使用B.PickTarget(self)
而不是self.PickTarget()
in B.Update(self)
得到这种行为。否则,切换A
and B
in C
的定义。
Edit:
如果预期行为是为了B
始终调用方法B
并为A
始终调用方法A
, it's correct to use A.method(self)
代替self.method()
,因为第二种形式并不意味着method
is in A
.
你应该重新设计你的课程。A
应该有一个移动方法来随机移动机器人并定义它的其他基本行为。B
应该是一个子类A
并且应该有一个调用的 move 方法super(B, self).move()
如果它没有路径,则在路径上移动。这是根据条件重写方法的正确方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)