【问题标题】:python async special class methods __delete__python异步特殊类方法__delete__
【发布时间】:2017-04-07 01:49:15
【问题描述】:

直截了当:

我如何在 python 中 async def__delete__ 这样的特殊类方法?

为什么我需要这个:

为了实现一个在多个进程之间共享的良好缓存系统,我想从数据库中检索一次数据并将它们存储在缓存中,修改缓存中的数据以及不再使用数据时:更新数据库。我的问题是,为了知道哪个实例是最后一个,我想异步使用 __delete__ 特殊方法

def asyncinit(cls):
    """Credits: http://stackoverflow.com/a/33140788/4241798"""
    __new__ = cls.__new__

    async def init(obj, *arg, **kwarg):
        await obj.__init__(*arg, **kwarg)
        return obj

    def new(cls, *arg, **kwarg):
        obj = __new__(cls, *arg, **kwarg)
        coro = init(obj, *arg, **kwarg)
        return coro

    cls.__new__ = new
    return cls

@asyncinit
class AsyncUser:
    async def __init__(self, id: int):
        self.id = id
        with await cachepool as cache:
            cache.hincr(f"users:{id}", "refcnt")

    async def __delete__(self):
        """Won't work"""
        with await cachepool as cache:
            refcnt = await cache.hincrby(f"users:{self.id}", "refcnt", -1)
            if refcnt == 0:
                # update database

    # rest of the class...

【问题讨论】:

  • 重复:请参阅此以获得答案。 stackoverflow.com/a/33134213/1943571
  • 我来自那里,这个答案不适用于__delete__的方法
  • 它在链接中说异步不适用于非异步魔术方法,包括 __delete__

标签: python class asynchronous


【解决方案1】:

异步 ​​def python 的内置方法是不可能的,但可以使用 loop.create_futureasyncio.ensure_future 在循环外安排协程调用

class asyncdel:
    def __delete__(self):
        asyncio.ensure_future(free(self.__dict__.copy()))

async def free(data):
    pass

【讨论】:

  • 据我所知,这在定义之前是行不通的,因为您正在调用一个函数。
  • 定义类时没有调用函数
猜你喜欢
  • 2014-05-14
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 2014-07-15
  • 2022-01-23
  • 2019-02-26
相关资源
最近更新 更多