所以......假设你正在构建这样的东西......它在工厂方法中构建一个类的实例。然后你会得到你报告的错误。看看回溯......泡菜试图做的是pickle.save_global
用来序列化你的课程。构建在函数内部,但在 中__main__
,该类实际上被命名__main___.Object
......并且没有__main__.Object
类......它嵌套在object_factory
命名空间内。在 python 中,工厂方法被大量用于动态构建类、实例、函数和其他对象。如果您使用的是工厂方法,则可以改为在另一个类中而不是函数中构建工厂方法......与现在相比,pickler 能够序列化 Object 类的实例的机会更大.
>>> def object_factory(a,b):
... c = a+b
... class Object(object):
... d = 1
... e = [c, d, [1,2,3]]
... def foo(self, x):
... return (self.d * c) + (x * Object.e)
... return Object()
...
>>> A = object_factory([4,5],[6,7])
>>> A
<__main__.Object object at 0x973030>
>>> A.d
1
>>> A.e
[[4, 5, 6, 7], 1, [1, 2, 3]]
>>> A.foo(1)
[4, 5, 6, 7, [4, 5, 6, 7], 1, [1, 2, 3]]
>>>
>>> _A = pickle.dumps(A)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 1366, in dumps
Pickler(file, protocol).dump(obj)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 224, in dump
self.save(obj)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 401, in save_reduce
save(args)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 562, in save_tuple
save(element)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 753, in save_global
(obj, module, name))
pickle.PicklingError: Can't pickle <class '__main__.Object'>: it's not the same object as __main__.Object
发布您的代码或至少一些演示您的问题的玩具代码会有所帮助。