使用带pickle的\uughtstate\uuu setstate_uu失败,错误为“ValueError:size needs be(int width,int height)”

2024-10-01 11:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图pickle pygame.Surface对象,它在默认情况下是不可pickle的。我所做的就是将经典的picklability函数添加到类中并覆盖它。这样它就可以和我的其他代码一起工作了。在

class TemporarySurface(pygame.Surface):
    def __getstate__(self):
        print '__getstate__ executed'
        return (pygame.image.tostring(self,IMAGE_TO_STRING_FORMAT),self.get_size())

    def __setstate__(self,state):
        print '__setstate__ executed'
        tempsurf = pygame.image.frombuffer(state[0],state[1],IMAGE_TO_STRING_FORMAT)
        pygame.Surface.__init__(self,tempsurf)

pygame.Surface = TemporarySurface

下面是一个我尝试提取一些递归对象时的回溯示例:

^{pr2}$

令我困惑的是print语句没有被执行。是否正在调用__getstate__?我在这里很困惑,我也不太确定应该提供什么信息。如果有什么额外的帮助,请告诉我。在


Tags: to对象imageselfstringdefsurfacepygame
1条回答
网友
1楼 · 发布于 2024-10-01 11:20:05

作为the documentation says,pickle扩展类型的主要入口点是__reduce__或{}方法。给定错误,默认的__reduce__实现似乎与pygame.Surface的构造函数不兼容。在

因此,最好为Surface提供一个__reduce__方法,或者通过copy_reg模块在外部注册一个方法。我建议后者,因为它不涉及猴子修补。你可能想要这样的东西:

import copy_reg

def pickle_surface(surface):
    return construct_surface, (pygame.image.tostring(surface, IMAGE_TO_STRING_FORMAT), surface.get_size())

def construct_surface(data, size):
    return pygame.image.frombuffer(data, size, IMAGE_TO_STRING_FORMAT)

construct_surface.__safe_for_unpickling__ = True
copy_reg.pickle(pygame.Surface, pickle_surface)

这应该是你所需要的。但是,请确保construct_surface函数在模块的顶层可用:取消拾取进程需要能够定位该函数才能执行取消拾取过程(这可能发生在不同的解释器实例中)。在

相关问题 更多 >