A question about whether or not I’m going about something in the best way…
I would like to have a class hierarchy in Python that looks (minimally) like the following;
class Actor
class Mover(Actor)
class Attacker(Actor)
class Human(Mover, Attacker)
But I run up against the fact that Actor has a certain attribute which I’d like to initialise, from each of the Mover and Attacker subclasses, such as in below;
class Actor:
_world = None
def __init__(self, world):
self._world = world
class Mover(Actor):
_speed = 0
def __init__(self, world, speed):
Actor.__init__(self, world)
self._speed = speed
class Attacker(Actor):
_range = 0
def __init__(self, world, range):
Actor.__init__(self, world)
self._range = range
If I was then to go with my initial approach to this, and follow what I always have in terms of using superclass’ constructors, I will obviously end up calling the Actor constructor twice – not a problem, but my programmer sense tingles and says I’d rather do it a cleaner way;
class Human(Mover, Attacker):
def __init__(self, world, speed, range):
Mover.__init__(self, world, speed)
Attacker.__init__(self, world, range)
I could only call the Mover constructor, for example, and simply initialise the Human‘s _range explicitly, but this jumps out at me as a much worse approach, since it duplicates the initialisation code for an Attacker.
Like I say, I’m aware that setting the _world attribute twice is no big deal, but you can imagine that if something more intensive went on in Actor.__init__, this situation would be a worry. Can anybody suggest a better practice for implementing this structure in Python?
What you’ve got here is called diamond inheritance. The Python object model solves this via the method resolution order algorithm, which uses C3 linearization; in practical terms, all you have to do is use
superand pass through**kwargs(and in Python 2, inherit fromobject):Note that you now need to construct
Humanwith kwargs style:What actually happens here? If you instrument the
__init__calls you find that (renaming the classes toA, B, C, Dfor conciseness):D.__init__callsB.__init__B.__init__callsC.__init__C.__init__callsA.__init__A.__init__callsobject.__init__What’s happening is that
super(B, self)called on an instance ofDknows thatCis next in the method resolution order, so it goes toCinstead of directly toA. We can check by looking at the MRO:For a better understanding, read Python’s super() considered super!
Note that
superis absolutely not magic; what it does can be approximated in Python itself (here just for thesuper(cls, obj)functionality, using a closure to bypass__getattribute__circularity):