[Python] AttributeError: object has no attribute dataclass python3.11

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    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)
    # this prints the dictionary correctly

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

    processMethod(t)



    I am getting a json value and deserializing in to objects using dataclass. In processMethod I am getting this error AttributeError: 'ttd' object has no attribute 'metadata'. Any suggestions please. I wanted to store the values in separate objects for ease of processing. I am not really familiar with inheritance and dataclasses and this in python 3.11

    Continue reading...

Compartilhe esta Página