[Python] How to make dataclass instance attribute non-public and an __init__ arg?

Discussão em 'Python' iniciado por Stack, Setembro 7, 2025.

  1. Stack

    Stack Membro Participativo

    If I want an instance attribute to be:

    • Non-public (aka have a single leading underscore)
    • Be a parameter in the __init__ signature

    Normally, I would do this:

    class Foo:
    def __init__(self, bar: str):
    self._bar = bar

    foo = Foo(bar="bar") # foo.bar would raise an AttributeError


    However, in dataclasses, I'm unsure how to do this.

    from dataclasses import dataclass

    @dataclass
    class Foo:
    bar: str # This leaves bar as a public instance attribute


    What is the correct way to do this in dataclasses.dataclass?

    Continue reading...

Compartilhe esta Página