定义时如何自动注册一个类 [英] How to auto register a class when it's defined
问题描述
当我定义类时,我想要有一个类注册的实例。理想情况下,下面的代码将会成功。
I want to have an instance of class registered when the class is defined. Ideally the code below would do the trick.
registry = {}
def register( cls ):
registry[cls.__name__] = cls() #problem here
return cls
@register
class MyClass( Base ):
def __init__(self):
super( MyClass, self ).__init__()
不幸的是代码生成错误 NameError:全局名称'MyClass'未定义
。
Unfortunately, this code generates the error NameError: global name 'MyClass' is not defined
.
code> #problem here line我试图实例化一个 MyClass
,但是装饰器还没有返回,所以它不存在
What's going on is at the #problem here
line I'm trying to instantiate a MyClass
but the decorator hasn't returned yet so it doesn't exist.
这是使用元类或某事吗?
Is the someway around this using metaclasses or something?
推荐答案
p>是的,元类可以做到这一点。元类' __ new __
方法返回类,所以只需在返回之前注册该类。
Yes, meta classes can do this. A meta class' __new__
method returns the class, so just register that class before returning it.
class MetaClass(type):
def __new__(cls, clsname, bases, attrs):
newclass = super(MetaClass, cls).__new__(cls, clsname, bases, attrs)
register(newclass) # here is your register function
return newclass
class MyClass(object):
__metaclass__ = MetaClass
上一个例子适用于Python 2.x。在Python 3.x中, MyClass
的定义略有不同(而$ code> MetaClass 未显示,因为它不变 - 除了 super(MetaClass,cls)
可以成为 super()
,如果你想):
The previous example works in Python 2.x. In Python 3.x, the definition of MyClass
is slightly different (while MetaClass
is not shown because it is unchanged - except that super(MetaClass, cls)
can become super()
if you want):
#Python 3.x
class MyClass(metaclass=MetaClass):
pass
这篇关于定义时如何自动注册一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!