python __setattr__ 导致定义变量的属性错误

python __setattr__ causes attribute error on a defined variable

每次调用“setattr”魔术方法时,都会由于某种原因导致属性错误。我收到一个属性错误,指出 'rect' 变量不存在,但它在 class.

中明确定义
import pygame as pg


class Block:
    blocks = {}
    id_ = 1

    def __init__(self, surface, name=None, color=[0] * 3, width=0):
        self.surface = surface
        self.name = (name if name else Block.id_)
        self.color = color
        self.width = width

        self.rect = pg.Rect((0, 0), [20] * 2)
        self.block = self.make_block()

        pg.draw.polygon(*self.block)

        Block.blocks[self.name] = self

        if not name:
            Block.id_ += 1

    def make_block(self):
        point_1 = self.rect.topleft
        point_2 = (self.rect.topleft[0], self.rect.topleft[1] + self.rect.size[1])
        point_3 = (point_2[0] + self.rect.size[0], point_2[1])
        point_4 = (point_3[0], point_1[0])

        return [self.surface, self.color, (point_1, point_2, point_3, point_4), self.width]

    def __setattr__(self, name, value):
        pass


Block(pg.Surface((20, 20)))

您忽略了 __setattr__ 什么都不做。那就是设置属性的地方。举这个小例子:

In [3]: class Rect:
   ...:     def __init__(self):
   ...:         self.length = 12
   ...:         self.width = 5
   ...:     def __setattr__(self, name, val):
   ...:         print(f"attempting to set {name}={val}")
   ...:

In [4]: r=Rect()
attempting to set length=12
attempting to set width=5

In [5]: r.length
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-1697af2cfc88> in <module>
----> 1 r.length

AttributeError: 'Rect' object has no attribute 'length'

因为我覆盖了它并且没有实际设置它,所以没有为我的 class 设置任何属性。所以当我尝试访问它时,它会导致错误。我猜这就是你正在经历的。如果你想解决这个问题,那么你需要在覆盖它时设置属性,而不仅仅是 pass.