Python MixIn标准

2024-05-13 23:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在编写一些代码,最近遇到了实现一些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

基本上,我在想,mix-in是否有点像Java接口,其中有一种契约(Python的情况是隐式的),如果想要使用代码,必须定义某些变量/函数(不像框架),还是更像我上面写的代码,每个mix-in都必须显式初始化?在


Tags: 代码inrectselfinitdefpositionupdate
1条回答
网友
1楼 · 发布于 2024-05-13 23:11:08

在Python中可以同时具有这两种行为。可以通过使用抽象基类或在虚拟函数中引发NotImplementedError来强制实现。在

如果init在父类中很重要,则必须调用它们。正如eryksun所说,使用super内置函数来调用父级的初始值设定项(这样,给定类的初始值设定项将只被调用一次)。在

结论:取决于你拥有什么。在您的例子中,您必须调用init,并且应该使用super。在

相关问题 更多 >