[Python] Python dataclasses, inheritance and alternate class constructors

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, I am using dataclass with the following class hierarchy:

    from dataclasses import dataclass

    @dataclass
    class Foo:
    id: str

    @classmethod
    def fromRaw(cls, raw: dict[str, str]) -> 'Foo':
    return Foo(raw['id'])

    @dataclass
    class Bar(Foo):
    name: str

    @classmethod
    def fromRaw(cls, raw: dict[str, str]) -> 'Bar':
    return Bar(raw['id'], raw['name'])


    However, it feels a bit double to instantiate all Foo members manually again in Bar::fromRaw().

    Is there a better way to re-use the ancestor's alternate constructor for example?

    Continue reading...

Compartilhe esta Página