我有一个制作精灵flyweight的类,我正在使用装饰器来调用这个类。这是一些代码:
class flyweight:
def __init__(self, cls):
self._cls = cls
self.__instances = dict()
def __call__(self, title):
return self.__instances.setdefault((title), self._cls(title))
在这个问题中,我将简化代码以显示相关内容。
@flyweight
class Sprite:
def __init__(self, title, surf=None):
self.title = title
self.surf = surf if surf is not None else pygame.image.load('Images/Sprites/'+title+'.png').convert_alpha()
self.w, self.h = self.surf.get_size()
@staticmethod
def from_colour(colour, size=(40,40)):
surf = pygame.Surface(size).convert(); surf.fill(colour)
return Sprite(colour, surf)
red = Sprite.from_colour((125,0,0))
但这给了我错误:
AttributeError: 'flyweight' object has no attribute 'from_colour'
我应该改造我的轻量级实现还是有办法解决这个问题?