总是指向其他属性的功能

时间:2019-08-27 10:19:14

标签: python class pygame

我正在努力改进pythonic编码,想知道是否有一种方法可以始终指向同一类中的属性函数(包括“更新”其值)

简化代码如下:

class xyz:
    def __init__(self, widht, height):
        self.image = pygame.Surface((width, height))
        self.rect = self.image.get_rect()
obj = xyz(42, 42)
obj.image = pygame.Surface((some_other_width, some_other_height))
# obj.rect would still be of size 42x42 and not the new values

由于图像的大小是变化的,所以变化非常频繁,并且我的班级必须具有一个名为rect的属性,其属性为当前图像的大小,这也许是一种神奇的方法,可以实现update_rect()函数的工作(尝试播放有点与self__getattribute()__在一起,但这没用)

def update_rect(self):
    self.rect.width, self.rect.height = self.image.get_width(), self.image.get_height()

1 个答案:

答案 0 :(得分:2)

正如jonrsharpe在评论中建议的那样,您可以使用属性。但是像这样将image设为属性,而不是rect

import pygame

class xyz(pygame.sprite.Sprite):
    def __init__(self, width, height):
        super().__init__()
        self._image = pygame.Surface((width, height))
        self.rect = self.image.get_rect()

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, value):
        self._image = value
        self.rect = self._image.get_rect(topleft=self.rect.topleft)

obj = xyz(42, 42)
obj.rect.topleft = (300, 300)

print(obj.rect.width)   # prints 42
print(obj.rect.x)       # prints 300

obj.image = pygame.Surface((100, 100))

print(obj.rect.width)   # prints 100
print(obj.rect.x)       # prints 300

这样,您还可以保留通常存储在rect属性中的位置。