让我们考虑含有ASYNCIO环和一个异步协程类的下面的例子:Python中,ASYNCIO:装饰类,以简化循环语法
import asyncio
class Async:
def __init__(self):
self.loop=asyncio.get_event_loop()
async def function(self, word):
print(word)
await asyncio.sleep(1.0)
a=Async()
a.loop.run_until_complete(a.function("hello_world"))
这确实工作。
我想创建一个装饰,这样我可以简化代码调用function
的语法
a.function("hello_world")
我试过如下:
class Async:
def __init__(self):
self.loop=asyncio.get_event_loop()
def async_loop(f):
def decorated(*args, **kwargs):
self.loop.run_until_complete(f(*args, **kwargs))
@async_loop
async def function(self, word):
print(word)
await asyncio.sleep(1.0)
a=Async()
a.function("hello_world")
在这一点上我收到的错误:'NoneType' object is not callable
。 - 我也尝试在类之外拥有装饰器功能,但我得到了同样的错误。我不确定装饰器功能是否最好地站在claass(作为方法)内部或外部。 我对Python非常陌生,所以类中的Asyncio,装饰器和装饰器对我来说仍然相当混乱。任何好的灵魂会有一个想法如何正确地执行该代码?
你犯了一个经典失误。 'async_loop'必须返回'装饰的'。 – PaulMcG
@PaulMcG ok是的 - 现在我收到其他错误,相对于'self.loop',它仍然是超级混乱如何在我的课堂做装饰,所以在这里的帮助将非常感谢,因为weel –