Generic metaclass to keep track of subclasses?

前端 未结 3 1202
生来不讨喜
生来不讨喜 2021-02-20 05:26

I\'m trying to write a generic metaclass to track subclasses

Since I want this to be generic, I didn\'t want to hardcode any class name within this metaclass, therefore

3条回答
  •  别跟我提以往
    2021-02-20 06:14

    I think you want something like this (untested):

    class SubclassTracker(type):
        def __init__(cls, name, bases, dct):
            if not hasattr(cls, '_registry'):
                cls._registry = []
            print('registering %s' % (name,))
            cls._registry.append(cls)
            super(SubclassTracker, cls).__init__(name, bases, dct)
    

    Then, for Python 2, you can invoke it like:

    class Root(object):
        __metaclass__ = SubclassTracker
    

    for Python 3

    class Root(object, metaclass=SubclassTracker):
    

    Note that you don't need to stick the _registry attribute on there because stuff like that is what metaclasses are for. Since you already happen to have one laying around... ;)

    Note also that you might want to move the registration code into an else clause so that the class doesn't register itself as a subclass.

提交回复
热议问题