Cea*_*sta 7 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
Run Code Online (Sandbox Code Playgroud)
基本上,我想知道,混合类似于Java接口,其中有一种(在Python的情况下隐含)合同,如果有人希望使用代码,则必须定义某些变量/函数(与框架不同) ,或者它更像我上面编写的代码,其中每个混合必须显式初始化?
您可以在 Python 中同时拥有这两种行为。您可以通过使用抽象基类或通过在虚拟函数中引发 NotImplementedError 来强制重新实现。
如果init在父类中很重要,那么您必须调用它们。正如 eryksun 所说,使用super内置函数调用父级的初始值设定项(这样,给定类的初始值设定项只会被调用一次)。
结论:取决于你拥有什么。在你的情况下,你必须调用init,并且应该使用super.