Python 扩展pygame sprite类

Python 扩展pygame sprite类,python,class,pygame,Python,Class,Pygame,所以我正在用pygame用python编写一个游戏,我为我的不同精灵创建了单独的类(pygame.sprite.sprite类型),但是它们都共享很多共同的物理代码。我如何扩展基本的sprite类,以便只编写一次普通的物理内容,并且只向每个需要的sprite类添加特定于类的内容 e、 g.改变这一点: class ShipSprite(pygame.sprite.Sprite): def __init__(self, start_position=(500,500)):

所以我正在用pygame用python编写一个游戏,我为我的不同精灵创建了单独的类(pygame.sprite.sprite类型),但是它们都共享很多共同的物理代码。我如何扩展基本的sprite类,以便只编写一次普通的物理内容,并且只向每个需要的sprite类添加特定于类的内容

e、 g.改变这一点:

class ShipSprite(pygame.sprite.Sprite):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def common_physics_stuff()
        pass

    def ship_specific_stuff()
        pass

class AsteroidSprite(pygame.sprite.Sprite):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def common_physics_stuff()
        pass

    def asteroid_specific_stuff()
        pass
进入这个

class my_custom_class()
    def common_physics_stuff()
        pass

class ShipSprite(my_custom_class):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def ship_specific_stuff()
        pass

class AsteroidSprite(my_custom_class):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def asteroid_specific_stuff()
        pass

只需从
Sprite
继承中间类,然后从中继承:

class my_custom_class(pygame.sprite.Sprite):
    def common_physics_stuff()
        pass

class ShipSprite(my_custom_class):
    ...
如果您想将“自定义_类”内容添加到一个抽象类中,该类的行为不必像精灵一样,并且可以在其他上下文中使用,那么您也可以使用多重继承-

class my_custom_class(object):
    def common_physics_stuff()
        pass

class ShipSprite(pygame.sprite.Sprite, my_custom_class):
    ...
但这可能是杀伤力过大了——在这两种情况中的任何一种情况下,在游戏类中覆盖的任何方法上,只需记住使用
super
Python内置调用适当的祖先方法即可


(在我的小游戏项目中,我通常为从Pygame的Sprite继承的所有对象创建一个“GameObject”基类)

你不能使用
my_custom_类(Pygame.Sprite.Sprite)
让你的自定义对象从基类继承吗?