Python MixIn Standards

So, I am writing code and recently encountered the need to implement several mixins. My question is, what is the correct way to develop mixing? I will use the code example below to illustrate my exact request.

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 

Basically, I'm interested in these are mixed objects like Java interfaces, where there is a kind of (in the case of Python implicit) contract, which, if you want to use the code, must define certain variables / functions (as opposed to a framework), or is it more like the code i wrote above where each mix should be initialized explicitly?

+6
source share
1 answer

You can have both behaviors in Python. You can force re-implementation using abstract base classes or by raising a NotImplementedError in virtual functions.

If init is important in parent classes, you must call them. As eryksun said, use the built-in super function to call the parent initializers (thus, the initializer for this class will be called only once).

Conclusion: Depends on what you have. In your case, you need to call init , and you have to use super .

+2
source

Source: https://habr.com/ru/post/894680/


All Articles