首页 > 解决方案 > 更改子类的父类的未知属性

问题描述

我想用父类 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 对象的属性顶部。

标签: pythonooppygame

解决方案


我不明白这里有什么问题。你self.top是 0,这就是为什么yin self.rectvalue 也是 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)>,因此您应该专注于修复循环。


推荐阅读