AttributeError:对象没有属性数据类python3.11

问题描述 投票:0回答:1
from dataclasses import dataclass, field
from datetime import datetime
from typing import List as PyList
import json

@dataclass
class metadata:
 docType:str

@dataclass
class spr:
 sprType:str

@dataclass
class nMI:
 idx:int

@dataclass
class bene:
 bid:int
 put:str

@dataclass
class ttd(metadata,spr,nMI):
 bn:list[bene]


json_str = '''{
  "docType":"abc",
  "sprType":"def",
  "idx":2,
  "bn":[{
     "bid":3, "put":"out"}]
}'''

def printMethod(t:metadata):
    print(t)

def printMethod1(t:spr):
    print(t)

def processMethod(t:ttd):
  printMethod(t.metadata) 
  printMethod1(t.spr)


data = json.loads(json_str)

t=ttd(**data)

print(t)

# ttd(idx=2, sprType='def', docType='abc', bn=[{'bid': 3, 'put': 'out'}])

processMethod(t)

# this prints the dictionary correctly

我正在获取 json 值并使用数据类反序列化为对象。在 processMethod 中,我收到此错误 AttributeError: 'ttd' object has no attribute 'metadata'。有什么建议请。我想将这些值存储在单独的对象中以便于处理。我不太熟悉继承和数据类以及 python 3.11 中的

python python-dataclasses
1个回答
0
投票

相反::

@dataclass
class ttd(metadata, spr,nMI):
 bn:list[bene]

用途:

@dataclass
class Ttd:
    metadata: Metadata
    spr: Spr
    nmi: NMI
    bn: list[Bene]

这样您就可以访问您的元数据实例

© www.soinside.com 2019 - 2024. All rights reserved.