问题描述
我想创建自己的 MagicCursor 类.我希望它从 sqlite3.Cursor() 继承所有方法和属性.但在他的情况下看起来并不那么容易.
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()
因为两者之间存在联系.所以我想我必须定义我自己的Connection Class,然后定义我自己的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.
这是我想要实现的:
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
有人知道如何实现吗?
推荐答案
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
在这个例子中,super(MyConnect, self).cursor(MyCursor)
调用sqlite3.Connection.cursor(MyCursor)
.
In this example, super(MyConnect, self).cursor(MyCursor)
callssqlite3.Connection.cursor(MyCursor)
.
sqlite3.Connection.cursor 接受一个可选的参数,cursorClass
.提供时,即用于实例化游标的类.
sqlite3.Connection.cursor accepts an optional argument, cursorClass
. When supplied, that is the class used to instantiate the cursor.
这篇关于Python:如何成功继承Sqlite3.Cursor并添加我自定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!