Python MixIn标准

时间:2011-08-09 21:34:20

标签: python design-patterns mixins

所以我正在编写一些代码,并且最近遇到了实现一些mixin的需要。我的问题是,设计混合的正确方法是什么?我将使用下面的示例代码来说明我的确切查询。

class Projectile(Movable, Rotatable, Bounded):
    '''A projectile.'''
    def __init__(self, bounds, position=(0, 0), heading=0.0):
        Movable.__init__(self)
        Rotatable.__init__(self, heading)
        Bounded.__init__(self, bounds)
        self.position = Vector(position)

    def update(self, dt=1.0):
        '''Update the state of the object.'''
        scalar = self.velocity
        heading = math.radians(self.heading)
        direction = Vector([math.sin(heading), math.cos(heading)])
        self.position += scalar * dt * direction
        Bounded.update(self)

class Bounded(object):
    '''A mix-in for bounded objects.'''
    def __init__(self, bounds):
        self.bounds = bounds

    def update(self):
        if not self.bounds.contains(self.rect):
            while self.rect.top > self.bounds.top:
                self.rect.centery += 1
            while self.rect.bottom < self.bounds.bottom:
                self.rect.centery += 1
            while self.rect.left < self.bounds.left:
                self.rect.centerx += 1
            while self.rect.right > self.bounds.right:
                self.rect.centerx -= 1

基本上,我想知道,混合类似于Java接口,其中有一种(在Python的情况下隐含)合同,如果一个人希望使用代码,则必须定义某些变量/函数(不同于一个框架),还是更像我上面写的代码,每个混合必须明确初始化?

1 个答案:

答案 0 :(得分:2)

你可以在Python中同时拥有这两种行为。您可以使用Abstract Base Classes或通过在虚函数中引发NotImplementedError来强制重新实现。

如果 init 在父类中很重要,那么您必须调用它们。正如eryksun所说,使用super内置函数来调用父级的初始化器(这样,给定类的初始化器只会被调用一次)。

结论:取决于你拥有的东西。在您的情况下,您必须致电 init ,并且应使用super