描述符的方法 [英] Methods on descriptors
问题描述
我正在尝试围绕 redis 数据库实现一个包装器,该数据库进行一些簿记,并且我考虑过使用描述符.我有一个包含一堆字段的对象:帧、失败等,我需要能够获取、设置,并根据需要增加字段.我试图实现一个 Int-Like 描述符:
I'm trying to implement a wrapper around a redis database that does some bookkeeping, and I thought about using descriptors. I have an object with a bunch of fields: frames, failures, etc., and I need to be able to get, set, and increment the field as needed. I've tried to implement an Int-Like descriptor:
class IntType(object):
def __get__(self,instance,owner):
# issue a GET database command
return db.get(my_val)
def __set__(self,instance,val):
# issue a SET database command
db.set(instance.name,val)
def increment(self,instance,count):
# issue an INCRBY database command
db.hincrby(instance.name,count)
class Stream:
_prefix = 'stream'
frames = IntType()
failures = IntType()
uuid = StringType()
s = Stream()
s.frames.increment(1) # float' object has no attribute 'increment'
似乎我无法访问我的描述符中的 increment() 方法.我不能在 __get__ 返回的对象中定义增量.如果我想做的只是增加,这将需要一个额外的数据库查询!我也不想在 Stream 类上使用 increment() ,因为稍后当我想在 Stream 中有额外的字段(如字符串或集合)时,我需要键入检查所有内容.
Is seems like I can't access the increment() method in my descriptor. I can't have increment be defined in the object that the __get__ returns. This would require an additional db query if all I want to do is increment! I also don't want increment() on the Stream class, as later on when I want to have additional fields like strings or sets in Stream, then I'd need to type check the heck out of everything.
推荐答案
试试这个:
class IntType(object):
def __get__(self,instance,owner):
class IntValue():
def increment(self,count):
# issue an INCRBY database command
db.hincrby(self.name,count)
def getValue(self):
# issue a GET database command
return db.get(my_val)
return IntValue()
def __set__(self,instance,val):
# issue a SET database command
db.set(instance.name,val)
这篇关于描述符的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!