我试图找出如何链类的方法来提高一个工具类我已经写 - 的原因,我不希望进入:)Python的描述符链方法
现在假设我想链上的一个类实例链类方法(在这种情况下,如何设置光标),例如:
# initialize the class instance
db = CRUD(table='users', public_fields=['name', 'username', 'email'])
#the desired interface class_instance.cursor(<cursor>).method(...)
with sql.read_pool.cursor() as c:
db.cursor(c).get(target='username', where="omarlittle")
是交代不清的是,我宁愿光标不坚持作为类属性的部分.get(...)
后就一直称为并已返回,我想要求首先调用.cursor(cursor)
。
class CRUD(object):
def __init__(self, table, public_fields):
self.table = table
self.public_fields = public_fields
def fields(self):
return ', '.join([f for f in self.public_fields])
def get(self, target, where):
#this is strictly for illustration purposes, I realize all
#the vulnerabilities this leaves me exposed to.
query = "SELECT {fields} FROM {table} WHERE {target} = {where}"
query.format(fields=self.fields, table=self.table, target=target,
where=where)
self.cursor.execute(query)
def cursor(self, cursor):
pass # this is where I get lost.
为什么被标记为“元编程”,为什么标题中的“描述符”?在你的问题或任何可能的答案中,似乎没有任何元编程技术或描述符的用法...... – abarnert