使用装饰器自动注册类方法 [英] Auto-register class methods using decorator

查看:27
本文介绍了使用装饰器自动注册类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够创建一个 python 装饰器,自动在全局存储库中注册"类方法(具有一些属性).

I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties).

示例代码:

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...

我希望加载完成后,某处会有一个包含以下内容的字典:

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 ) }

这可能吗?

推荐答案

不仅仅是装饰器,不是.但是元类可以在创建后自动与类一起使用.如果您的 register 装饰器只是记录元类应该做什么,您可以执行以下操作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆