0

I am trying to create a module that wraps all classes, and use them somewhere else.

class Mixins:
    class B:
        pass

    class C:
        pass


b = Mixins.B()
print(Mixins.__all_subclasses__())
# [Mixins.B, Mixins.C]

I mean, I can stack all subclasses in a list after I created one, but not elegant. is there an instinctive built-in for me to do this? python 3.7.

2 Answers 2

1

You can check inspect module

import inspect


class Mixins:
    class B:
        pass

    class C:
        pass


print(inspect.getmembers(Mixins, lambda x: inspect.isclass(x)))
# [('B', <class '__main__.Mixins.B'>), ('C', <class '__main__.Mixins.C'>), ('__class__', <class 'type'>)]
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this by subclassing the Mixin class directly and then accessing the __subclasses__ method on the Mixin class

class Mixin:
    pass


class B(Mixin):
    pass


class C(Mixin):
    pass


print(Mixin.__subclasses__())

which prints

[<class '__main__.B'>, <class '__main__.C'>]

any class that inherits from Mixin is automatically available in __subclasses__ and you don't have to manually maintain the list of "Known" instances.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.