撇开使用isinstance 是否有害,我在通过 Pickle 序列化/反序列化对象后尝试评估 isinstance 时遇到了以下难题:
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__)
谁能解释为什么 isinstance 在这种情况下会失败?换句话说,为什么 Python 认为这些对象属于两个不同的类?当我删除第二类定义时,isinstance
工作正常。