Python使用super()实现方法返回值与跟踪内部状态的问题
问题原因
你的代码运行异常和super()的特性无关,属于基础的代码执行顺序错误:
在修改后的Shape.draw()方法中,你将return语句放在了self.has_run = True状态更新代码之前,Python执行到return时会直接终止当前方法的运行,后续的状态更新代码、super().draw()调用永远不会被执行,因此has_run始终保持初始值False,每次调用都会走首次执行的分支。
修正方案
调整代码顺序,将状态更新、父类方法调用放在return之前即可:
class Root: def draw(self): # the delegation chain stops here assert not hasattr(super(), 'draw') class Shape(Root): def __init__(self, shapename, **kwds): self.shapename = shapename self.has_run = False super().__init__(**kwds) def draw(self): if not self.has_run: print('Drawing for the first time. Setting shape to:', self.shapename) self.has_run = True res = 'a' else: print('Drawing again. Setting shape to:', self.shapename) res = 'b' super().draw() return res class ColoredShape(Shape): def __init__(self, color, **kwds): self.color = color super().__init__(**kwds) def draw(self): print('Drawing. Setting color to:', self.color) foo = super().draw() return [foo] * 3 cs = ColoredShape(color='blue', shapename='square') print('*** first pass') out = cs.draw() print(out) print('*** second pass') out = cs.draw() print(out)
运行结果
*** first pass Drawing. Setting color to: blue Drawing for the first time. Setting shape to: square ['a', 'a', 'a'] *** second pass Drawing. Setting color to: blue Drawing again. Setting shape to: square ['b', 'b', 'b']
内容的提问来源于stack exchange,提问作者bmeyers
相关产品推荐
相关产品推荐

