[Python] Statically get all attributes of class

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    I want to be able to call a static method of a class (or classmethod) to only get the attributes of that class. By the attributes of the class, I mean the ones that are set in the constructor of the class. I also use inheritance, so I would like to be able to do this for both MyClass and MyChildClass.

    class MyClass():
    def __init__(self, x = None, y = None):
    self.a = x
    self.b = y

    @classmethod
    def get_all_attr(cls):
    return ?

    class MyChildClass():
    def __init__(self, z = None, **kwargs):
    self.c = z
    super().__init__(**kwargs)

    >>> MyClass.get_all_attr()
    ['a', 'b']
    >>> MyChildClass.get_all_attr()
    ['c', 'a', 'b']



    I know that __dir__() exists, but I have not been able to call this statically. I've also tried MyClass.__dict__().keys(), but this also won't work.

    Continue reading...

Compartilhe esta Página