自动注册类方法使用装饰器 [英] Auto-register class methods using decorator
本文介绍了自动注册类方法使用装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要创建一个自动注册类方法在全局库(具有一些属性)的python装饰器。
I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties).
示例代码: p>
Example code:
class my_class(object):
@register(prop1,prop2)
def my_method( arg1,arg2 ):
# method code here...
@register(prop3,prop4)
def my_other_method( arg1,arg2 ):
# method code here...
我想要当加载完成时,某处会有一个dict,包含: / p>
I want that when loading is done, somewhere there will be a dict containing:
{ "my_class.my_method" : ( prop1, prop2 )
"my_class.my_other_method" : ( prop3, prop4 ) }
这是可能吗?
推荐答案
不只是装饰师,没有。但是,一个类可以在创建后自动使用类。如果您的注册
装饰器只是记录元类应该做什么,您可以执行以下操作:
Not with just a decorator, no. But a metaclass can automatically work with a class after its been created. If your register
decorator just makes notes about what the metaclass should do, you can do the following:
registry = {}
class RegisteringType(type):
def __init__(cls, name, bases, attrs):
for key, val in attrs.iteritems():
properties = getattr(val, 'register', None)
if properties is not None:
registry['%s.%s' % (name, key)] = properties
def register(*args):
def decorator(f):
f.register = tuple(args)
return f
return decorator
class MyClass(object):
__metaclass__ = RegisteringType
@register('prop1','prop2')
def my_method( arg1,arg2 ):
pass
@register('prop3','prop4')
def my_other_method( arg1,arg2 ):
pass
print registry
打印
{'MyClass.my_other_method': ('prop3', 'prop4'), 'MyClass.my_method': ('prop1', 'prop2')}
这篇关于自动注册类方法使用装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文