泛型元类来跟踪子类? [英] Generic metaclass to keep track of subclasses?
问题描述
我正在尝试编写一个通用的元类来跟踪子类
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 I came up with a function that generates the proper metaclass, something like:
def make_subtracker(root):
class SubclassTracker(type):
def __init__(cls, name, bases, dct):
print('registering %s' % (name,))
root._registry.append(cls)
super(SubclassTracker, cls).__init__(name, bases, dct)
return SubclassTracker
这样,我可以调用它来为特定的 root 类生成一个元类,
This way I could invoke it to generate a metaclass for a specific root class with:
__metaclass__ = make_subtracker(Root)
这是我遇到问题的地方.我不能这样做:
Here is where I bump into a problem. I cannot do this:
class Root(object):
_registry = []
__metaclass__ = make_subtracker(Root)
...因为使用make_subtracker(Root)
时尚未定义Root
.我稍后尝试添加__metaclass__属性,以便至少可以将其应用于子类:
...because Root
is not defined yet when I use make_subtracker(Root)
. I tried adding the __metaclass__ attribute later, so that at least it can be applied in subclasses:
class Root(object):
_registry = []
Root.__metaclass__ = make_subtracker(Root)
...但这不起作用.读取类定义时,__metaclass__具有特殊处理,如自定义类创建.
...but this doesn't work. __metaclass__ has a special processing when the class definition is read, as defined in Customizing class creation.
我正在为此寻求建议(或者在运行时以将其应用于子类的方式更改类的元类,或者其他任何替代方法).
I'm looking for suggestions in order to do this (either change a class' metaclass at runtime in a way that it is applied to its subclasses, or any other alternative).
推荐答案
Python针对新类自动执行此操作,如本在这里.
Python does this automatically for new-style classes, as mentioned in this answer to the similar queston How to find all the subclasses of a class given its name? here.
这篇关于泛型元类来跟踪子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!