我如何将自己附加到另一个模块的 function/class?

How would I attach self to another module's function/class?

我目前正在制作一个模块,可以更轻松地使用 sqlite3 编写数据库,我的功能之一如下:

def fetch(cursor, tableName, target = "*", condition = None, fetchType = "all"): # Fetches data from a table in a database
    "Fetches data from a table in a database\nExecutes 'SELECT {target} FROM {tableName} WHERE {condition}' on the cursor\nExample: user1Name = fetch(cursor, 'tblUser', target = 'userName', condition = 'userId = 1', fetchType = 'one')"

    if condition != None: cursor.execute(f"SELECT {target} FROM {tableName} WHERE {condition}") # Selects values if there is a condition

    else: cursor.execute(f"SELECT {target} FROM {tableName}") # Selects targets if there is not a condition

    if fetchType == "all": return cursor.fetchall() # Fetches all values

    elif fetchType == "one": return cursor.fetchone() # Fetches one value

    else: raise Exception("Invalid fetchType.") # Raises an exception if the user is trying to use an invalid fetchType

我基本上想找到一种方法来实现它,而不是调用 var = fetch(cursor... 我可以调用 var = cursor.fetch(tableName... 以便于访问,因为我只是想知道我将来会怎么做.

这叫做monkey-patching,这在动态语言中很常见。找到 cursor 的 class(我们称之为 CursorClass),然后猴子修补它。第一个参数将作为 self:

def fetch(cursor, table, ...)
    # cursor will act as self inside this functon
    ...

# Make sure that you do not override an
# existing attribute on CursorClass
CursorClass.fetch = fetch

# Then you can call fetch on the cursor
cursor = CursorClass(...)
cursor.fetch('TableName', ...)