如何在 Python 中创建具有两个不同变量参数的类实例?



这段代码有两个类,看起来类Player()Block()有相同的代码,我想最小化代码,所以我不重复那样的咒语,这样做的方法是类的实例,Player()Block()的实例,如何?

class Block(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()

self.image = pygame.Surface([20, 15])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
self.change_x += x
self.change_y += y

def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y

在从你们那里寻找答案后,代码就像这样:

class Block(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
class Player(Block):
def __init__(self, color, width, height, x, y):

Block.__init__(self, color, width, height)
self.rect.x = x
self.rect.y = y
self.change_x = 0
self.change_y = 0
def changespeed(self, x, y):
self.change_x += x
self.change_y += y

def update(self):
self.rect.x += self.change_x
self.rect.y += self.change_y 

那段代码是真的吗?当我运行该程序时,它可以工作。

就像 Player 和 Block 从pygame.sprite.Sprite继承一样,你可以让 Player 从 Block 继承:

class Player(Block):

然后,调用super().__init__()以使用 Block 的构造函数(而 Block 的构造函数也会调用pygame.sprite.Sprite的构造函数(:

class Player(Block):
def __init__(self, x, y):
super().__init__()

然后在此之下,添加特定于播放器的所有代码。

添加一个中产阶级:

class Middle(pygame.sprite.Sprite):
super().__init__()
self.image = pygame.Surface([20, 15])
self.image.fill(BLUE)
self.rect = self.image.get_rect()

然后类块和类玩家继承自中产阶级

最新更新