【发布时间】:2015-08-22 21:28:41
【问题描述】:
所以我正在使用 pygame 在 python 中编写游戏,并且我为我的不同精灵有单独的类(类型为 pygame.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
【问题讨论】:
-
你不能只使用
my_custom_class(pygame.sprite.Sprite)让你的自定义继承基类吗?