我有一个自定义类的对象,该对象与pickle.dump一起存储到.pickle文件中。看来我可以在文件中的另一个cmd会话中pickle.load这个对象,而只用相应的名称定义一个空类。 这是预期的行为还是我错过了一些东西?有可能需要注意的地方吗?
dopickle.py:
import pickle
class TestObject:
def __init__(self, name: str):
self.name = name
self.numbers = ["one", "two", "three"]
def main():
test = TestObject("a name")
with open("test.pickle", "wb") as f:
pickle.dump(test, f)
if __name__ == "__main__":
main()
unpickle.py:
import pickle
class TestObject:
pass
def main():
with open("test.pickle", "rb") as f:
test_object = pickle.load(f)
print(test_object.name)
print(test_object.numbers)
if __name__ == "__main__":
main()