0

The encoding is basically string representation of a dictionary, containing the object's fields. However, a dictionary does not respect order, and I could potentially get different encoding string on different runs. How do I preclude this from happening? Or should I use another library where I can ensure deterministic encoding?

By deterministic encoding, I mean if I create 100000 objects that are practically the same, i.e. same class and same constructor args, when I call encode() on each one of them, I get the exact same string every time.

So, for example, if I have

class MyClass(object):
   def __init__(self, a, b):
      self.a = a
      self.b = b

c1 = MyClass(1, 2)

c2 = MyClass(1, 2)

I want to be sure that the strings encode(c1) and encode(c2) are perfectly identical, character for character, i.e.

assert jsonpickle.encode(c1)==jsonpickle.encode(c2)
4

1 回答 1

0

我认为 jsonpickle 会处理你所说的确定性 endocing。

例子

import jsonpickle
class Monopoly(object):

    def __init__(self):
        self.boardwalk_price = 500

    @property
    def boardwalk(self):
        self.boardwalk_price += 50
        return self.boardwalk_price



m = Monopoly()
serialized = jsonpickle.encode(m)

看一眼

print (serialized)
{"py/object": "__main__.Monopoly", "boardwalk_price": 500}

现在,让我们解码

d = jsonpickle.decode(serialized)
print (d)
<__main__.Monopoly object at 0x7f01bc093278>
d.boardwalk_price
500

为了比较对象,Python 使用标识符。

class MyClass(object):
   def __init__(self, a, b):
      self.a = a
      self.b = b

c1 = MyClass(1, 2)
c2 = MyClass(1, 2)

如果你看一下 id

id(c1)
140154854189040
id(c2)
140154854190440
c1 == c2

False

您可以覆盖eq运算符

def __eq__(self, x):
    if isinstance(x, number):
        return self.number == x.number
    return False
于 2018-08-23T05:00:14.687 回答