简体   繁体   English

装饰器将实例方法转换为类函数

[英]Decorator to convert an instance method into a class function

I need to pass several methods as callbacks which don't take the self argument. 我需要传递一些不使用self参数的方法作为回调。 This is how my current code looks like: 这是我当前的代码如下所示:

def _do_callback(callback, log, *args):
    try:
        # some common code
        callback(*args)
    except:
        log.error('XX')

class Foo(object):
    def __init__(self):
        self.log = Log('Foo')
        self.cb1_wrapper = lambda x: _do_callback(self.cb1, self.log, x)  # I need a function taking one parameter
        self.cb2_wrapper = lambda x: _do_callback(self.cb2, self.log, x)

    def cb1(self, x):
        # some code accessing self

    def cb2(self, x):
        # some code accessing self

    def register_callbacks(self):
        register('1', self.cb1_wrapper)
        register('2', self.cb2_wrapper)

Is it possible to write some decorator to apply to cb1 and cb2 to be able to pass the result into code that currently takes self.cb1_wrapper ? 是否可以编写一些装饰器以应用于cb1cb2以便将结果传递到当前需要self.cb1_wrapper代码中?

(I know the title is not ideal, feel free to edit) (我知道标题不太理想,随时可以编辑)

Sure; 当然; just think about how an unwrapped method should look: 只需考虑一个解开的方法应该看起来如何:

def callback(fn):
    def inner(self, *args):
        return _do_callback(fn.__get__(self, type(self)), self.log, *args)
    return inner

class Foo(object):
    def __init__(self):
        self.log = Log('Foo')

    @callback
    def cb1_wrapped(self, x):
        pass

I don't know about a decorator, but you could easily write a "wrapper function" that turns out a bound method to a "callback". 我不了解装饰器,但是您可以轻松编写一个“包装函数”,该包装函数将绑定方法变为“回调”。 Something like that: 这样:

def wrap(bound_method):
    return lambda x: _do_callback(bound_method, bound_method.__self__.log, x)

The one (major?) drawback is that you have to use the wrapper at call time: 一个(主要吗?)缺点是您必须在调用时使用包装器:

foo = Foo()
...
my_fnc_using_callback(wrap(foo.cb1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM