如何解决python __setattr__ 导致定义变量的属性错误
每次调用 '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)))
解决方法
你忽略了 __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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。