Python: How to successfully inherit Sqlite3.Cursor and add my customized method

StackOverflow https://stackoverflow.com/questions/23683886

  •  23-07-2023
  •  | 
  •  

Frage

I want to make my own MagicCursor class. I want it to inherit all method and attributes from sqlite3.Cursor(). But it looks not that easy in t his case.

usually we create a cursor like this:

import sqlite3
conn = sqlite3.connect('test.db')
crs = conn.cursor()

because there's a connection in between. So I think I have to define my own Connection Class and then define my own Cursor.

Here's what I want to implement:

import sqlite3
conn = MyConnect('test.db') ## this returns me a connect object, inherit from         sqlite3.Connection 
crs = conn.cursor() ## this returns me a MyCursor class,
                ## which inherit from sqlite3.Cursor() and has my customized method

Here's my code, but failed.

class MyConnect(sqlite3.Connection):
    def cursor(self):
        return MyCursor(self)

class MyCursor(sqlite3.cursor):
    def __init__(self, connect):
        self = connect.cursor()

    def mymethod1(self, argv)
         ...... return ...... ## what ever I defined

Anyone got an idea how to implement that?

War es hilfreich?

Lösung

import sqlite3
class MyConnect(sqlite3.Connection):
    def cursor(self):
        return super(MyConnect, self).cursor(MyCursor)

class MyCursor(sqlite3.Cursor):
    def mymethod1(self, argv):
        print('Got here')

conn = sqlite3.connect(':memory:', factory=MyConnect)
print(conn)
# <__main__.MyConnect object at 0x90db66c>

cursor = conn.cursor()
print(cursor)
# <__main__.MyCursor object at 0x90d19dc>

cursor.mymethod1('foo')
# Got here

In this example, super(MyConnect, self).cursor(MyCursor) calls sqlite3.Connection.cursor(MyCursor).

sqlite3.Connection.cursor accepts an optional argument, cursorClass. When supplied, that is the class used to instantiate the cursor.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top