私のプロジェクトの 1 つでjsonpickle
、同じファイルから実行する限りは問題なく動作しますが、別のクラスから実行すると、ターゲット オブジェクトが dict に変更されます。以下は簡単な問題の再構成です。私の元のクラスは少し複雑ですが、問題は同じです。
gui.py
PS 問題は、(他のコードのリファクタリングを使用して)に変更import data
すると「消える」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 !
2 番目のファイルがエラーを返します:
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'