在我的一个项目中,我遇到了一个奇怪的问题jsonpickle
,只要我从同一个文件运行它就可以正常工作,但是如果它是从其他类运行的,它会将目标对象更改为 dict。下面是简单的问题重构。我原来的课程有点复杂,但问题是一样的。
gui.py
当我更改import data
为(使用其他代码重构)时,PS 问题“消失”,from data import *
但我不确定为什么......
简单的例子:
- 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
- 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'