2017-08-04 72 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

你知道裝飾器已經做到了嗎?我看了一下,但沒有找到任何裝飾器。 –