【发布时间】: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