首页 > 解决方案 > 如何在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 

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

标签: pythonpython-3.xpygamepygame-surface

解决方案


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

class Player(Block):

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

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

然后在其下,添加特定于 Player 的所有代码。


推荐阅读