【问题标题】:python __setattr__ causes attribute error on a defined variablepython __setattr__ 导致定义变量的属性错误
【发布时间】:2021-01-01 20:28:29
【问题描述】:

每次调用 'setattr' 魔术方法时,由于某种原因,它都会导致属性错误。我收到一个属性错误,说“rect”变量不存在,但它已在类中明确定义。

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)))

【问题讨论】:

  • 但是你忽略了它什么都不做。所以它实际上并没有定义......
  • 错误是:AttributeError: 'Block' object has no attribute 'rect' [Finished in 0.1s with exit code 1]

标签: python-3.x pygame setattr


【解决方案1】:

你覆盖__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'

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

【讨论】:

  • 我试过了,还是不行。唯一受到影响的变量是 rect 变量,所以它不可能是因为我没有设置它,否则错误会在 rect 变量之前发生,对吧?
  • 你试过不覆盖__setattr__吗?你一开始是有原因的吗?
  • 是的,我需要它来更新动画的矩形值。是的,没有 setattr 它可以正常工作,但仅适用于静态对象,但我需要它才能为动画工作。
  • 我不太确定为什么,但是当我添加 object.__setattr__(self, name, value) 时,它以某种方式工作,这很奇怪,因为我似乎定义了两次相同的函数。
猜你喜欢
  • 1970-01-01
  • 2018-09-28
  • 2013-03-27
  • 2018-02-16
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
相关资源
最近更新 更多