【问题标题】:Jsonpickle in subclass changes data type子类中的 Jsonpickle 更改数据类型
【发布时间】:2020-04-27 16:09:32
【问题描述】:

在我的一个项目中,jsonpickle 有一个奇怪的问题,只要我从同一个文件运行它就可以正常工作,但是如果它是从其他类运行的,它会将目标对象更改为 dict。下面是简单的问题重构。我原来的类有点复杂,但问题是一样的。

附:在gui.py 中问题“消失”我将import data 更改为from data import *(使用其他代码重构)但我不知道为什么......

简单示例:

  1. data.py - 单独工作正常
import jsonpickle
from dataclasses import dataclass, field
from typing import List

@dataclass
class Car:
    name: str
    model: str

class CarsList(List):
    # some other non important functions

    def length(self):
        return len(self)

class Company:

    def __init__(self):
        self.companyCars = CarsList()
        self.loadData()
        print(self.companyCars.length())

    def loadData(self):
        with open('cars.json', "r") as infile:
            json_str = infile.read()
        self.companyCars = jsonpickle.decode(json_str)

if __name__ == '__main__':
    myCompany = Company()  # works fine
  1. gui.py(不工作)
import data
class Gui:
    def __init__(self):
        self.myCompany = data.Company()

if __name__ == '__main__':
    myGui = Gui()  # Not working !

第二个文件返回错误:

Traceback (most recent call last):
  File "/home/bart/costam/gui.py", line 15, in <module>
    myGui = Gui()  # Not working !
  File "/home/bart/costam/gui.py", line 11, in __init__
    self.myCompany = data.Company()
  File "/home/bart/costam/data.py", line 40, in __init__
    print(self.companyCars.length())
AttributeError: 'dict' object has no attribute 'length'

【问题讨论】:

    标签: python jsonpickle


    【解决方案1】:

    该类在全球范围内不可用,因此jsonpickle 无法对其进行解码。

    docsThe object must be accessible globally via a module and must inherit from object (AKA new-style classes).

    这也是当您执行from data import * 时问题“消失”的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多