【发布时间】:2009-03-06 23:17:27
【问题描述】:
抛开是否使用isinstance is harmful 不谈,在通过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 工作正常。
【问题讨论】:
-
你为什么要换班?您正在创建一个具有相似名称的新对象。但是有什么意义呢?
-
这是一个玩具示例。在实践中,假设我想腌制一个对象,将其通过电线发送,然后在另一侧将其解开。接收端需要有一个单独的类定义,这就是我要在这里演示的。
-
@Ben Hoffstein:除了你不是,因为这一切都在一个过程中。试着把它分成两部分来做一个更真实的例子。
-
感谢所有有用的答案。我以前没有使用过 isinstance,现在对它的工作原理有了更好的了解。