擅长:python、mysql、java
<p>您可以将共享功能放入mixin类中</p>
<pre><code>import random
class AbstractRobot:
"""My 1 dimensional robot"""
def __init__(self, start_at):
self.pos = start_at
class RobotMoveMixin:
def move(self, delta):
self.pos += delta
print('moved to', self.pos)
class GoodRobot(RobotMoveMixin, AbstractRobot):
pass
class BadRobot(RobotMoveMixin, AbstractRobot):
def move(self, delta):
print("bad robot")
if random.choice((True, False)):
super().move(delta)
robot = BadRobot(0)
for _ in range(10):
robot.move(3)
</code></pre>
<p>现在好机器人和它的继承者得到了好的动作,而坏机器人和它的干涉者得到了混乱的动作</p>