当我在查看aiortc示例时,我注意到一个具有方法的装饰器:
@pc.on("datachannel")
def on_datachannel(channel):
...我真的不明白这是如何工作的,或者这段代码是做什么的。我一直在搜索装饰器,我知道有可能有类装饰器,但没有使用方法。有没有人能详细说明一下?
发布于 2020-08-06 18:37:50
@foo
def bar(): ...这种语法只是为了实现以下目的:
def bar(): ...
bar = foo(bar)所以,这是:
@pc.on('datachannel')
def on_datachannel(channel): ...与以下内容相同:
def on_datachannel(channel): ...
on_datachannel = pc.on('datachannel')(on_datachannel)pc是一个对象,pc.on是它的一个方法,pc.on('datachannel')调用它,它返回一个函数,pc.on('datachannel')(on_datachannel)调用返回的函数,传递给它on_datachannel函数。
pc.on的实现如下所示:
class PC:
def on(self, event):
...
def wrapper(fn):
...
def inner_wrapper(*args, **kwargs):
...
fn(*args, **kwargs)
return inner_wrapper
return wrapper
pc = PC()所有这些内部部分完全是一个接受参数的常规装饰器。它是在一个类上定义的,这对它没有影响。
https://stackoverflow.com/questions/63281498
复制相似问题