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?