[Python] Is it possible to limit attributes in a Python sub class using __slots__?

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

  1. Stack

    Stack Membro Participativo

    One use of __slots__ in Python is to disallow new attributes:

    class Thing:
    __slots__ = 'a', 'b'

    thing = Thing()
    thing.c = 'hello' # error


    However, this doesn’t work if a class inherits from another slotless class:

    class Whatever:
    pass

    class Thing(Whatever):
    __slots__ = 'a', 'b'

    thing = Thing()
    thing.c = 'hello' # ok


    That’s because it also inherits the __dict__ from its parent which allows additional attributes.

    Is there any way of blocking the __dict__ from being inherited?

    It seems to me that this would allow a sub class to be less generic that its parent, so it’s surprising that it doesn’t work this way naturally.

    Continue reading...

Compartilhe esta Página