【发布时间】:2020-12-26 23:03:45
【问题描述】:
我想用父类 pygame.Rect 创建一个子类 Cell,但我无法更改 Cell 类实例的属性 top 并且它只是设置为零。 我的代码是:
import pygame
light = pygame.Color('#D3D3D3')
dark = pygame.Color('#222222')
class Cell(pygame.Rect):
def __init__(self, index, side):
self.index = index
self.side = side
self.color = None # Index is a tuple from (0, 0) to (2, 2)
self.has_pawn = None
# Setting coordinates
for i in range(3):
if index[1] == i:
self.x = i*self.side
if index[0] == i:
self.y == (2-i)*self.side
self.left = self.x
self.top = self.y
self.width = self.side
self.height = self.side
# self.rect = pygame.Rect(x, y, width, height)
# Setting color
sum = self.index[0] + self.index[1]
if sum % 2 == 0:
self.color = light
if sum % 2 == 1:
self.color = dark
# Setting has_pawn
if index[0] == 0 | index[1] == 2:
self.has_pawn = True
b2 = Cell((1, 1), 5)
print(b2)
给出输出:
pygame 2.0.1 (SDL 2.0.14, Python 3.9.1)
Hello from the pygame community. https://www.pygame.org/contribute.html
<rect(5, 0, 5, 5)>
[Finished in 0.6s]
希望有人能帮我把Cell对象的属性top改一下。
【问题讨论】:
-
你可能需要调用
super().__init__(),并传入适当的参数,这样父类才能初始化这些属性。 -
我不知道使用打印功能时使用的“适当参数”到底是什么。所以,我不知道我是否使用了 super().__init__(top) 什么的。