为什么在腌制后在Python isinstance中会出现意外行为? [英] Why do I get unexpected behavior in Python isinstance after pickling?
问题描述
抛开使用 isinstance是否有害,我遇到了通过Pickle对对象进行序列化/反序列化后尝试评估isinstance时遇到以下难题:
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:
from __future__ import with_statement
import pickle
# Simple class definition
class myclass(object):
def __init__(self, data):
self.data = data
# Create an instance of the class
x = myclass(100)
# Pickle the instance to a file
with open("c:\\pickletest.dat", "wb") as f:
pickle.dump(x, f)
# Replace class with exact same definition
class myclass(object):
def __init__(self, data):
self.data = data
# Read an object from the pickled file
with open("c:\\pickletest.dat", "rb") as f:
x2 = pickle.load(f)
# The class names appear to match
print x.__class__
print x2.__class__
# Uh oh, this fails...(why?)
assert isinstance(x2, x.__class__)
任何人都可以阐明为什么ininstance在这种情况下会失败吗?换句话说,为什么Python认为这些对象属于两个不同的类?当我删除第二个类定义时,isinstance
可以正常工作.
Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance
works fine.
推荐答案
解吸程序的工作方式如下(site-packages/pickle.py):
This is how the unpickler works (site-packages/pickle.py):
def find_class(self, module, name):
# Subclasses may override this
__import__(module)
mod = sys.modules[module]
klass = getattr(mod, name)
return klass
查找并实例化一个类.
因此,如果您用相同名称的类替换一个类,则klass = getattr(mod, name)
将返回新类,并且该实例属于该新类,因此isinstance将失败.
So of course if you replace a class with an identically named class, the klass = getattr(mod, name)
will return the new class, and the instance will be of the new class, and so isinstance will fail.
这篇关于为什么在腌制后在Python isinstance中会出现意外行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!