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はこれらのオブジェクトが2つの異なるクラスのものだと思いますか? 2番目のクラス定義を削除すると、isinstance
が正常に動作します。
なぜあなたはクラスを置き換えていますか?同じ名前の新しいオブジェクトを作成しています。しかし、何がポイントですか? –
これはおもちゃの例です。実際には、オブジェクトをピケッとし、ワイヤで送信し、反対側でアンピクルしたいとします。受信側は、私がここでデモンストレーションしようとしているクラスの別の定義を持つ必要があります。 –
@Ben Hoffstein:それはすべてが1つのプロセスであるためではありません。より現実的な例を作るために2つに分解してみてください。 –