龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

Python pickle类库介绍(对象序列化和反序列化)(2)

时间:2014-11-22 02:28来源:网络整理 作者:网络 点击:
分享到:
def __getstate__(self): # Copy the object's state from self.__dict__ which contains # all our instance attributes. Always use the dict.copy() # method to avoid modifying the original state. state = se

    def __getstate__(self):
        # Copy the object's state from self.__dict__ which contains
        # all our instance attributes. Always use the dict.copy()
        # method to avoid modifying the original state.
        state = self.__dict__.copy()
        # Remove the unpicklable entries.
        del state['file']
        return state

    def __setstate__(self, state):
        # Restore instance attributes (i.e., filename and lineno).
        self.__dict__.update(state)
        # Restore the previously opened file's state. To do so, we need to
        # reopen it and read from it until the line count is restored.
        file = open(self.filename)
        for _ in range(self.lineno):
            file.readline()
        # Finally, save the file.
        self.file = file
       
reader = TextReader("hello.txt")
print(reader.readline())
print(reader.readline())
s = pickle.dumps(reader)
#print(s)
new_reader = pickle.loads(s)
print(new_reader.readline())

# the output is
# 1: hello
# 2: how are you
# 3: goodbye


精彩图集

赞助商链接