编码基本上是字典的字符串表示,包含对象的字段。然而,字典并不遵循顺序,我可能会在不同的运行中得到不同的编码字符串。我怎么才能避免这种情况发生呢?或者我应该使用另一个可以确保确定性编码的库?
通过确定性编码,我的意思是如果我创建了100000个实际上相同的对象,即相同的类和相同的构造函数参数,当我对每个对象调用encode()时,每次都会得到完全相同的字符串。
举个例子,如果我有
class MyClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
c1 = MyClass(1, 2)
c2 = MyClass(1, 2)我希望确保字符串encode(c1)和encode(c2)是完全相同的,即逐个字符。
assert jsonpickle.encode(c1)==jsonpickle.encode(c2)发布于 2018-08-23 13:00:15
示例
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 Falsehttps://stackoverflow.com/questions/51978421
复制相似问题