I’m starting to define my Entity classes for a game I am writing. However, I want a lot of code re-use. I want to define classes for different functionality, and then have classes which ‘have’ some of these classes’ functionality.
For example:
class Collidable:
def handle_collision(other, incident_vector):
pass
def __init__(self, shape):
self.shape = shape
class Movable:
def update_position(self):
self.velocity += self.acceleration
self.position += self.velocity
def __init__(self, velocity, acceleration):
self.velocity, self.acceleration = velocity, acceleration
class Drawable:
def draw(self):
pass
def __init__(self, image):
self.image = image
class Controllable:
def key_down(self, key):
pass
def __init__(self):
pass
Then have a Player class which is Collidable, Movable, Drawable, Controllable, an Invisible Barrier which is only Collidable, a Background which is only Drawable, etc. I’ve heard of many different ways of connecting multiple classes, (such as via Composition, (Multiple) Inheritance, Interfaces, etc), but I don’t know which is most appropriate and/or pythonic for this situation.
Mix-ins (special case of Multiple Inheritance) looks to be what I’m looking for (since a Player should BE a Collidable, a Movable, a Drawable, and a Controllable), but in trying this out, I’m finding difficulty in using super to pass the right arguments to the right init functions.
Edit:
I’m using python 3.2.
Here is a simple way to implement the inheritance using
super(). For this to work you will always need to create instances ofPlayer(and other classes that inherit from your ***able classes) with keyword arguments. Each base class will strip whatever keyword arguments it is using fromkwargsand pass the rest on to the next__init__()in the mro, for example:Then you could define your
Playerclass:And use it like this:
If you need additional instance variables for the
Playerclass you would define an__init__()similar to the other classes, for example: