Python, asyncio: class 中的装饰器以简化循环语法

Python, asyncio: decorator in class to simplify loop syntax

让我们考虑以下包含异步循环和异步协程的 class 示例:

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。 - 我还尝试在 class 之外使用装饰器函数,但我遇到了同样的错误。我不确定装饰器函数最好位于类内部(作为一种方法)还是外部。 我对 python 很陌生,所以 classes 中的 Asyncio、装饰器和装饰器对我来说仍然很混乱。任何善良的人都会知道如何正确地执行该代码吗?

classes 中的装饰器一团糟,因为 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 内声明事件循环,你可以做得更多 "selfless",或者更好的是,在 class 之外声明装饰器:

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")

所以现在开始提出问题,"why is this in a class in the first place?"还有一个问题,"isn't there a decorator out there that does this already?"