2017-08-04 69 views
1

让我们考虑含有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,装饰器和装饰器对我来说仍然相当混乱。任何好的灵魂会有一个想法如何正确地执行该代码?

+0

你犯了一个经典失误。 'async_loop'必须返回'装饰的'。 – PaulMcG

+0

@PaulMcG ok是的 - 现在我收到其他错误,相对于'self.loop',它仍然是超级混乱如何在我的课堂做装饰,所以在这里的帮助将非常感谢,因为weel –

回答

1

课室内的装修师一团糟,因为self必须随处可见。

这里是你的代码的工作版本:

import asyncio 

class Async: 
    def __init__(self): 
     self.loop=asyncio.get_event_loop() 

    def async_loop(f): 
     def decorated(self, *args, **kwargs): 
      self.loop.run_until_complete(f(self, *args, **kwargs)) 
     return decorated 

    @async_loop 
    async def function(self, word): 
     print(word) 
     await asyncio.sleep(1.0) 

a=Async() 
a.function("hello_world") 

你可以使它更“无私”,如果你只需要声明的事件循环内async_loop,甚至更好,声明类外的装饰:

def async_loop(f): 
    loop = asyncio.get_event_loop() 
    def decorated(*args, **kwargs): 
     loop.run_until_complete(f(*args, **kwargs)) 
    return decorated 

class Async: 
    @async_loop 
    async def function(self, word): 
     print(word) 
     await asyncio.sleep(1.0) 

a=Async() 
a.function("hello_world") 

所以现在开始提出这样一个问题:“为什么这是一个班级呢?”还有一个问题,“是不是有一个装饰者已经这样做了?”

+0

真棒thx。为什么'async_loop()'不需要async_loop(self,f)'?它仍然被认为是类Async的一种方法吗? –

+0

好问题。按照定义,它仍然是Async实例的绑定方法,我称之为“f”应该是“自我”。装饰者应该是静态方法,可以引导人们思考“也许装饰器不是一个好主意,看看我的编辑 – PaulMcG

+0

你知道装饰器已经做到了吗?我看了一下,但没有找到任何装饰器。 –