[英]Decorator to convert an instance method into a class function
我需要傳遞一些不使用self
參數的方法作為回調。 這是我當前的代碼如下所示:
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)
是否可以編寫一些裝飾器以應用於cb1
和cb2
以便將結果傳遞到當前需要self.cb1_wrapper
代碼中?
(我知道標題不太理想,隨時可以編輯)
當然; 只需考慮一個解開的方法應該看起來如何:
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
我不了解裝飾器,但是您可以輕松編寫一個“包裝函數”,該包裝函數將綁定方法變為“回調”。 像這樣:
def wrap(bound_method):
return lambda x: _do_callback(bound_method, bound_method.__self__.log, x)
一個(主要嗎?)缺點是您必須在調用時使用包裝器:
foo = Foo()
...
my_fnc_using_callback(wrap(foo.cb1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.