因此,我用python编写了一个用pygame编写的游戏,我为我的不同的精灵有不同的类(pygame.sprite.Sprite类型)--但是它们都有很多共同的物理代码。我如何扩展基本的sprite类,以便编写一次普通的物理材料,而我只需将特定于类的东西添加到每个sprite类中?
例如,从这方面作出的改变:
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
发布于 2015-06-08 08:36:47
只需从Sprite
继承您的中间类,然后从它继承:
class my_custom_class(pygame.sprite.Sprite):
def common_physics_stuff()
pass
class ShipSprite(my_custom_class):
...
如果您想将您的"custom_class“东西添加到一个不需要像雪碧那样的抽象类中,并且可以在其他上下文中使用,那么您也可以使用多重继承-
class my_custom_class(object):
def common_physics_stuff()
pass
class ShipSprite(pygame.sprite.Sprite, my_custom_class):
...
但这可能是过火了--在这两种情况中的任何一种情况下,在游戏类上覆盖的任何方法上,只需记住使用super
Python内置调用正确的祖先方法即可。
(在我的小游戏项目中,我通常会为继承自Pygame's Sprite的所有对象做一个"GameObject“基类)
https://stackoverflow.com/questions/30708728
复制