我如何从 psycopg2 继承? [英] How can I inherit from psycopg2?
问题描述
我正在尝试像这样继承 psycopg2:
I'm trying inherit psycopg2 like this:
import psycopg2
class myp(psycopg):
pass
ii = myp
ii.connect(database = "myDataBase", user = "myUser", password="myPassword")
然后它抛出一个错误:
class myp(psycopg2._psycopg):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
是否可以从 psycopg2 库中继承?
Is it possible to inherit from psycopg2 library?
我想使用不同的数据库,所以我只需要更改 MyDatabase 类.像包装纸一样的东西.例子:
I want to use different databases, so I just have to change the class MyDatabase. something like a wrapper. example:
import psycopg2
class MyDatabase(psycopg2):
def connect(self):
#do some stuff
return psycopg2.connect(database = "myDataBase", user = "myUser", password="myPassword")
对于 mysqldb导入 MySQL 数据库
for mysqldb import MySQLdb
class MyDatabase(MySQLdb)
def connect(self):
#do some stuff
return psycopg2.connect(database = "myDataBase", user = "myUser", password="myPassword")
和派生类类 MyDataBaseApp(MyDatabase):def add(self, myObjectClass):db = MyDatabase()cn = 无
and derived class class MyDataBaseApp(MyDatabase): def add(self, myObjectClass): db = MyDatabase() cn = None
try:
cn = db.connect()
cur = cn.cursor()
cur.execute ("INSERT ...",(myObjectClass.parameter1, myObjectClass.parameter2))
cn.commit()
except MyDatabase.DatabaseError, e:
print e
if cn:
cn.rollback()
finally:
if cn:
cn.close()
但根据文档我必须以另一种方式做,建议?
but according to the documentation I have to do it another way, suggestions?
推荐答案
Disclaimer: 我不熟悉 psycopg
Disclaimer: I'm not familiar with psycopg
更新
似乎文档建议对psycopg2进行子类化.extensions.connection
.然后,connect()
是一个仍可用于创建新连接的工厂函数,但您必须将您的类作为工厂提供,同样 根据文档
Seems the documentation recommends to subclass psycopg2.extensions.connection
. Then, connect()
is a factory function that can still be used to create new connections, but you have to provide your class as a factory, again according to the docs
完整的代码可能看起来更像(未经测试):
Full code may have to look more like (untested):
import psycopg2
class myp(psycopg2.extensions.connection):
pass
ii = connect(connection_factory=myp,
database = "myDataBase", user = "myUser", password="myPassword")
更新 2
使用更新的方法,您正在尝试构建具有不同/不同接口的新类.通常,组合比继承更好,参见 wikipedia 和 这个问题.
With the updated approach, you're trying to build new classes with different/divergent interfaces. Often, composition is better than inheritance, see wikipedia and this question.
这篇关于我如何从 psycopg2 继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!