[Python] How can I make Python classmethods act on a subclass; if that doesn't work, what...

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a script that needs to assign fonts to specific objects for rendering; I attempted to have it assign defaults to a kind of object by using a class method in a shared superclass for those objects.

    class BodyItem:
    # We need this class attribute to set it per class later
    fonts = {}

    # Expose a method to set class default fonts, so that the config module
    # doesn't have to play with the attributes directly
    @classmethod
    def set_default_font(cls, name : str, font : text.TextStyle) -> None:
    cls.fonts[name] = font


    What I'd wanted this to do was to be callable on each class that inherits from BodyItem to individually set a class wide default without having to reimplement the behavior with each subclass; is the reason that's not working just that I've misunderstood how python class methods work?

    (also, it's occurred to me that the fact that there's a single mutable object in the parent class might be the issue, but if that's the issue i'm not sure what to do other than manually write an empty fonts dictionary into every subclass)

    Continue reading...

Compartilhe esta Página