2016-12-08 10 views
0

Python 2.7.12およびパッケージcx_Oracleを使用して、パッケージ呼び出しの拡張クラスOracleCursorを作成しようとしています。私は、スーパークラスからメソッドを継承し、いくつかのカスタムメソッドで拡張したいだけです。cx_OracleからOracleCursorクラスを拡張する方法

まず私は

import cx_Oracle 

conn = cx_Oracle.connect(username, password, dsn) 
cursor = conn.cursor() 

OracleCursorを取得し、私は、一つは、それが

class ExtendedCursor(cx_Oracle.Cursor): 

    def hello_world(self): 
     print('Hello world') 


extended = ExtendedCursor(cursor) 

によって達成されるが、私はTypeError: argument 1 must be cx_Oracle.Connection, not OracleCursorを得ると思うだろう、次の

>>> type(cursor)Out[6]: 
OracleCursor 

>>> isinstance(cursor, cx_Oracle.Cursor) 
True 

を持っています。そのエラーは意味をなさない。また、クラスとして認識されないので、OracleCursorをスーパークラスとして使用することはできません。

答えて

3

カーソルがConnectionオブジェクトから返されます。 ExtendedCursorを返すカスタム接続を作成する必要があります。

import cx_Oracle as cxo 

class MyCursor(cxo.Cursor): 
    def helloWorld(self): 
     print "helloWorld" 

class MyConnection(cxo.Connection): 
    def cursor(self): 
     return MyCursor(self) 



if __name__ == '__main__': 
    conStr = '<user>/<password>@127.0.0.1:1521/xe' 
    db = MyConnection(conStr) 
    c = db.cursor() 

    print c 

    c.execute('select 1+1 from dual') 
    print(c.fetchall()) 

    c.helloWorld() 

リターン:

<__main__.MyCursor on <__main__.MyConnection to [email protected]:1521/xe>> 
[(2,)] 
helloWorld 
関連する問題