我试图通过使用@property
装饰器返回一个具有对象x、y、宽度和高度的新rect对象,为自定义类提供rect属性。
@property
def rect(self):
return pygame.Rect(self.x, self.y, self.width, self.height)
@rect.setter
def rect(self, new_rect):
self.x = new_rect.x
self.y = new_rect.y
self.width = new_rect.width
self.height = new_rect.height
我可以制作一个setter,用新的rect完全替换rect,适当地更新对象的属性,但有没有一种方法可以在rect的属性更新时使其工作(即object.rect.bottomright = [5, 3]
将创建rect,更新右下角的属性,并将更改应用于对象的x、y、宽度和高度(?如果我缺少更好的方法,我也会很感激。
我避免让rect
属性包含x
、y
、width
和height
,因为我不想在任何时候访问其中一个常见属性时都必须访问rect
属性,但我意识到我可以简单地对pygame.Rect
类进行子类化,以获得具有所有结果属性的效果。