1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Derived python dataclass cannot override default value?

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

  1. Stack

    Stack Membro Participativo

    In the following code snippet the dataclass Derived is derived from dataclass Base. The Derived dataclass is setting new default values for field1 and field2.

    from dataclasses import dataclass

    @dataclass
    class Base:
    field1: str
    field2: str = "default_base_string"


    @dataclass
    class Derived(Base):
    field1 = "default_string1"
    field2 = "default_string2"

    print(Derived())


    Because Derived is a dataclass and has set a default value for all member variables field1 and field2, I expected that I could simply initialize the class calling Derived(). However I get the following error:

    TypeError: Derived.__init__() missing 1 required positional argument: 'field1'


    Is it not possible to set the default value for a member variable in a derived dataclass, so that this member variable becomes optional in the autogenerated __init__() method? Must I always define my own __init__() method in the Derived class? Or am I doing something wrong here?

    Continue reading...

Compartilhe esta Página