python - 如何在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 的构造函数(反过来也会调用pygame.sprite.Sprite
的构造函数):
class Player(Block):
def __init__(self, x, y):
super().__init__()
然后在其下,添加特定于 Player 的所有代码。
推荐阅读
- jquery - XMLHttprequest 只保存 4 条数据,有时 3 或 1 条数据
- javascript - 在移动设备中显示来自后端的图像的问题
- asp.net-mvc - 如何在 Godaddy Windows 托管服务器上托管 asp.net 核心应用程序
- swift - 如何将 2 个发布者和擦除值合并到 Void?
- android - 如何在首次加载时获得离子权限
- javascript - 当值输入一个时元素的对齐被破坏
- css - 仅针对 Wordpress 网站的一页定位 CSS 伪选择器
- javascript - 使用 Google Apps 脚本转到包含今天日期的单元格
- node.js - 考虑到某些要求,让 JWT 永不过期可以吗?
- python - 向量加法和乘法,加法误差