[Tutor] Moveable and Animated Sprites

Peter Otten __peter__ at web.de
Mon Aug 15 10:44:52 CEST 2011


Jordan wrote:

> Is there a more Pythonic way to create the class
> "MoveableAnimatedSheetSprite" I am using multiple inheritance but I see
> that I am really loading the image twice when I call __init__ for
> "AnimatedSheetSprite" and "MoveableSprite". Should I just make a
> moveable class and have moveable items inherit it with out inheriting
> from "Sprite"?
> By the way the code does work as intended right now.
> Thank you in advance, if you need more code or what ever just let me know.

You can use super() to avoid duplicate method calls in a diamond-shaped 
inheritance tree. The vanilla example:


>>> class A(object):
...     def __init__(self):
...             print "A"
...             super(A, self).__init__()
...
>>> class B(A):
...     def __init__(self):
...             print "B"
...             super(B, self).__init__()
...
>>> class C(A):
...     def __init__(self):
...             print "C"
...             super(C, self).__init__()
...
>>> class D(B, C):
...     def __init__(self):
...             print "D"
...             super(D, self).__init__()
...
>>> D()
D
B
C
A
<__main__.D object at 0x7f5345de9d50>

In your code it's a bit harder because you need compatible method 
signatures. One way to achieve that is to rely on keyword arguments and then 
stick in **kw. To illustrate:

class Sprite(pygame.sprite.Sprite):
    def __init__(self, imageName, startx=0, starty=0, **kw):
        super(Sprite, self).__init__(self)
        ...

class MoveableSprite(Sprite):
    def __init__(self, imageName, **kw):
        super(MoveableSprite, self).__init__(imageName, **kw)
        speed = kw["speed"]
        ...

m = MoveableSprite("rumpelstiltskin", speed=10, category="fairy tale")

I usually don't get it right the first time, but here's what I think your 
update() method would become:

class Sprite(pygame.sprite.Sprite):
    pass # no need to implement update() here

class AnimatedSheetSprite(Sprite):
    def update(self):
        super(AnimatedSheetSprite, self).update()
        self.animate()

class MoveableSprite(Sprite):
    def update(self):
        super(MoveableSprite, self).update()
        self.move()
           
class MoveableAnimatedSheetSprite(MoveableSprite, AnimatedSheetSprite):
    pass # no need to implement update() here





More information about the Tutor mailing list