Python:为什么jsonpickle的工作方式因IDE而异?

时间:2017-03-31 05:08:47

标签: python pycharm python-idle jsonpickle

这个相同的代码将在IDLE和PyCharm上产生两个完全不同的输出。

代码:

import jsonpickle
class TestClass(object):
    def __init__(self, name):
        self.name = name
pickled = jsonpickle.encode(TestClass("Testing"))
pickled
unpickled = jsonpickle.decode(pickled)
unpickled

Python控制台中的输出:

>>> import jsonpickle
>>> class TestClass(object):
...     def __init__(self, name):
...         self.name = name
>>> pickled = jsonpickle.encode(TestClass("Testing"))
>>> pickled
'{"py/object": "__main__.TestClass", "name": "Testing"}'
>>> unpickled = jsonpickle.decode(pickled)
>>> unpickled
<__main__.TestClass object at 0x03AAD130>

IDLE控制台中的输出(几乎相同):

>>> import jsonpickle
>>> class TestClass(object):
        def __init__(self, name):
            self.name = name
>>> pickled = jsonpickle.encode(TestClass("Testing"))
>>> pickled
'{"py/object": "__main__.TestClass", "name": "Testing"}'
>>> unpickled = jsonpickle.decode(pickled)
>>> unpickled
<__main__.TestClass object at 0x039C94B0>

PyCharm控制台中的输出:

>>> import jsonpickle
>>> class TestClass(object):
        def __init__(self, name):
            self.name = name
>>> pickled = jsonpickle.encode(TestClass("Testing"))
>>> pickled
'{"py/object": "__builtin__.TestClass", "name": "Testing"}'
>>> unpickled = jsonpickle.decode(pickled)
>>> unpickled
{'py/object': '__builtin__.TestClass', 'name': 'Testing'}

我的主要问题是,正如您所看到的,字符串在PyCharm上没有得到正确的“unpickled”。它在编码时从一个对象变为一个字符串(这是正确的),但在解码时不会从字符串返回到对象。

另一个可能感兴趣的区别是,在IDLE中,类被命名为__main__.TestClass,而在PyCharm中它是__builtin__.TestClass,这有点奇怪,因为它绝对不是内置类。另外,我发现正确的内置类在__builtins__(带有“s”)而不是__builtin__内。

0 个答案:

没有答案