python对象 序列化、反序列化、比较eq例子

python对象 序列化、反序列化、比较eq的例子
具体代码如下:

import json
class cpv(object):
    def __init__(self, kv=None):
        if not isinstance(kv,dict):
            kv = {}
        not_Anticipation_key = set(kv) - {'a', 'b'}
        if not_Anticipation_key:
            print('warn:',not_Anticipation_key,'not Anticipat when init class cpv.')
            
        self.a = kv.get('a')
        self.b = kv.get('b')
        
    @property
    def dict(self):
        return {'a':self.a, 'b':self.b}
    @property
    def json(self):
        return json.dumps(self.dict)
    def save(self, to_path):
        with open(from_path,mode='w') as f:
            f.write(self.json)
    def load(self, from_path=None):
        with open(from_path) as f:
            kv=json.loads(f.read())
            self.__init__(kv)
    def __str__(self):
        return ':'+self.json
    def __eq__(self, other):
        print("A __eq__ called: %r == %r ?" % (self, other))
        return self.a == other.a and self.b == other.b

执行效果展示

kv = {"a":1,"b":2}
anone = cpv(kv)

b = cpv({"a":1,"b":2,'c':3})
anone.dict, anone.json,b.dict, b.json ,anone==b
>>>
warn: {'c'} not Anticipat when init class cpv.
A __eq__ called: <__main__.cpv object at 0x000001EDA251D8B0> == <__main__.cpv object at 0x000001EDA251DB80> ?
({'a': 1, 'b': 2},
 '{"a": 1, "b": 2}',
 {'a': 1, 'b': 2},
 '{"a": 1, "b": 2}',
 True)

你可能感兴趣的:(python,开发语言)