gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:34 25 4
gpt4 key购买 nike

我需要传递几个方法作为回调,这些方法不采用 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)

是否可以编写一些装饰器来应用于 cb1cb2能够将结果传递到当前需要 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

关于python - 装饰器将实例方法转换为类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24760825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com