当前位置: 首页 > 面试题库 >

使用装饰器自动注册类方法

晁砚
2023-03-14
问题内容

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

示例代码:

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

我希望加载完成后,某处将包含以下内容:

{ "my_class.my_method"       : ( prop1, prop2 )
  "my_class.my_other_method" : ( prop3, prop4 ) }

这可能吗?


问题答案:

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

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


 类似资料:
  • 问题内容: 尽管有很多关于将类用作装饰器的资源,但我找不到能处理装饰 方法 问题的资源。这个问题的目的是解决这个问题。我将发布自己的解决方案,但是当然也邀请其他所有人发布他们的解决方案。 标准装饰器类实现的问题是python不会创建装饰函数的绑定方法: 方法装饰者需要克服这一障碍。 要求 以前面示例中的类为例,预期将完成以下工作: 理想情况下,函数和签名以及类似属性也应保留。 问题答案: 通常,当

  • 问题内容: 考虑这个小例子: 哪个打印 为什么参数(应该是Test obj实例)没有作为第一个参数传递给装饰函数? 如果我手动进行操作,例如: 它按预期工作。但是,如果我必须事先知道某个函数是否装饰,它就破坏了装饰器的全部目的。这里的模式是什么,还是我误会了什么? 问题答案: tl; dr 您可以通过将类作为描述符并返回部分应用的函数来解决此问题,该函数从中应用对象作为参数之一,如下所示 实际问题

  • void register_modifier(string name, mixed impl) Use this to dynamically register modifier plugin. Pass in the template modifier name, followed by the PHP function that it implements it. 动态注册一个修饰器插件,需要

  • 问题内容: 有时,我创建一个装饰器类,如下所示: IntelliJ可以自动为我创建此类吗? 问题答案: 更新// 我注意到IntelliJ具有用于生成委托方法的“生成”选项。创建一个新类: 然后标记myInterface,转到“菜单”>“代码”>“委托方法”,选择要包装的所有方法,仅此而已。 //更新结束 您可以尝试“重构”->“用委派替换继承”重构。这样就应该能够做到。我称之为“使用Alt +

  • 本文向大家介绍基于Python 装饰器装饰类中的方法实例,包括了基于Python 装饰器装饰类中的方法实例的使用技巧和注意事项,需要的朋友参考一下 title: Python 装饰器装饰类中的方法 comments: true date: 2017-04-17 20:44:31 tags: ['Python', 'Decorate'] category: ['Python'] --- 目前在中文网