我試圖找出如何鏈類的方法來提高一個工具類我已經寫 - 的原因,我不希望進入:)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