正在定义一个足以解开自定义对象的空类

时间:2019-08-04 18:45:23

标签: python-3.x class pickle

我有一个自定义类的对象,该对象与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()

0 个答案:

没有答案