[Python] Reconciling dataclasses with property: None as default value [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    Following Dataclasses and property decorator, via this comment I ended up in this tutorial on how to define @property in a dataclass.

    I have modified the solution, it's attempt 5 (the last attempt), to use a None default value for the property.

    I ended up with:

    from dataclasses import dataclass, field

    @dataclass
    class Vehicle:
    wheels: int|None = None
    _wheels: int|None = field(init=False, repr=False, default=None)

    @property
    def wheels(self) -> int|None:
    print("getting wheels")
    return self._wheels

    @wheels.setter
    def wheels(self, wheels: int|None):
    print("setting wheels to", wheels)
    self._wheels = wheels


    Now when declaring an empty object

    Vehicle()


    I get

    setting wheels to <property object at 0x0000019DB0ADF100>
    getting wheels
    Vehicle(wheels=<property object at 0x0000019DB0ADF100>)


    Why do I get the property object instead of None?

    How can I properly define a None default value here?

    Continue reading...

Compartilhe esta Página