python - 更改子类的父类的未知属性
问题描述
我想用父类 pygame.Rect 创建一个子类 Cell 但我无法更改类 Cell 实例的属性顶部,它只是设置为零。我的代码是:
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 对象的属性顶部。
解决方案
我不明白这里有什么问题。你self.top
是 0,这就是为什么y
in self.rect
value 也是 0。在以下循环中,
# 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
i
在最后一次迭代中的值为,2
这意味着在最后一次迭代中会发生这种情况。
self.y == (2-2)*5 # 0*5 = 0
这导致self.y
设置为 0,而后者又设置self.top
为 0。因此,您得到您得到的结果也就不足为奇了。
如果你这样做
super().__init__(pygame.Rect(10, 10, 10, 10))
打印的结果实际上是 <rect(10, 10, 10, 10)>
,因此您应该专注于修复循环。
推荐阅读
- php - 将 $_POST 变量格式化为准备好的语句
- sql-server - SQL:将子查询转换为公用表表达式
- angular - 当用户点击选择元素的下拉菜单时如何显示更多数据?
- vue.js - Router Link 只更新活动类一次
- ibm-cloud-infrastructure - 如何在 Network Gateway vsrx 中先解除关联,然后再关联特定 VLAN
- asp.net - 访问控制:数据库强化问题
- jhipster - 在Tomcat下运行jHipster war文件
- text-to-speech - GSM SIM800C 文字转语音音频流
- flutter - 产生颤振(Xcode)testflight存档失败并带有多个命令
- javascript - 使用 SINGLE 函数从几个输入之一复制文本(按 ID)