7

撇开使用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工作正常。

4

3 回答 3

5

显而易见的答案,因为它不是同一类。

它是一个类似的类,但不一样。

class myclass(object):
    pass

x = myclass()

class myclass(object):
    pass

y = myclass()


assert id(x.__class__) == id(y.__class__) # Will fail, not the same object

x.__class__.foo = "bar"

assert y.__class__.foo == "bar" # will raise AttributeError
于 2009-03-06T23:24:32.590 回答
5

这就是 unpickler 的工作方式(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 将失败。

于 2009-03-06T23:28:57.620 回答
3

更改代码以打印idandx.__class__x2.__class__会发现它们是不同的:

$ python foo4.py
199876736
200015248
于 2009-03-06T23:22:08.820 回答