#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : qichun tang
# @Contact    : tqichun@gmail.com
from copy import deepcopy
from pickle import loads, dumps


class Example():
    def __init__(self, data):
        self.data = data

    def __reduce__(self):
        tmp_data = self.data
        self.data = None
        res = super(Example, self).__reduce__()
        try:
            return res
        except:
            pass
        finally:
            self.data = tmp_data

    def copy(self):
        tmp_data = self.data
        self.data = None
        res = deepcopy(self)
        self.data = tmp_data
        return res

    def pickle(self):
        tmp_data = self.data
        self.data = None
        res = dumps(self)
        self.data = tmp_data
        return res

    def __str__(self):
        return f"Example: data={self.data}"


if __name__ == '__main__':
    obj = Example([66, 66])
    pickle_copied = loads(obj.pickle())
    copied = obj.copy()
    print(pickle_copied)
    print(copied)
    print(obj)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐