0

我正在尝试腌制pygame.Surface对象,默认情况下不可腌制。我所做的是将经典的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

这是我尝试腌制一些递归对象时的回溯示例:

Traceback (most recent call last):
  File "dibujar.py", line 981, in save_project
    pickler.dump((key,value))
  File "/usr/lib/python2.7/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib/python2.7/pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python2.7/pickle.py", line 562, in save_tuple
    save(element)
  File "/usr/lib/python2.7/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/usr/lib/python2.7/copy_reg.py", line 71, in _reduce_ex
    state = base(self)
ValueError: size needs to be (int width, int height)

令我困惑的部分是打印语句没有被执行。__getstate__甚至被调用?我在这里很困惑,我不确定要提供什么信息。让我知道是否有任何额外的帮助。

4

1 回答 1

3

正如文档所说,腌制扩展类型的主要入口点是__reduce__or__reduce_ex__方法。鉴于该错误,默认实现似乎与' 的构造函数__reduce__不兼容。pygame.Surface

所以你最好提供一种__reduce__方法Surface,或者通过模块在外部注册一个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函数在模块的顶层可用:解酸过程需要能够定位该函数才能执行解酸过程(这可能发生在不同的解释器实例中)。

于 2012-12-07T07:47:00.387 回答