【发布时间】:2012-03-13 22:51:42
【问题描述】:
我在 Python 中使用类实例时遇到问题。 我创建了一个从 cx_Oracle 包继承连接类的新类 ora。 当我尝试运行此代码时,我会收到信息
文件“pyt.py”,第 12 行,在 myquery 中 ora.myConnect.cursor() AttributeError: 'NoneType' 对象没有属性 'cursor'
因此 Python 无法识别在 ora.myConnect 中存储了对实例的引用。
我不知道t know what can be reason of this error and what its 的代码有误。
from cx_Oracle import connect
class ora(connect):
myConnect = None
def __init__(self,connstr):
ora.myConnect = connect.__init__(self,connstr)
def myquery(self):
ora.myConnect.cursor()
ora.myConnect.cursor.execute("SELECT * FROM table")
ora.myConnect.cursor.close()
connstr = 'user/passwd@host:port/sid'
connection = ora(connstr)
connection.myquery()
connection.close()
编辑
我ve tried to replace ora to self but still Python dont 可以访问实例
from cx_Oracle import connect
class ora(connect):
myConnect = None
def __init__(self,connstr):
self.myConnect = connect.__init__(self,connstr)
def myquery(self):
self.myConnect.cursor()
self.myConnect.cursor.execute("SELECT * FROM table")
self.myConnect.cursor.close()
错误: self.myConnect.cursor() AttributeError: 'NoneType' 对象没有属性 'cursor'
EDIT2 这段代码在没有 OOP 的情况下工作,对我来说 self.myConnect 应该引用对象实例,并且这个对象应该包含方法 cursor()
import cx_oracle
connstr = 'user/passwd@host:port/sid'
connection = cx_oracle.connect(connstr)
cursor = connection.cursor()
cursor.execute("SELECT * FROM table")
cursor.close()
connection.close()
【问题讨论】:
-
self.myConnect = connect.__init__(self,connstr)很奇怪。__init__方法似乎不太可能返回游标。您确定您了解您要扩展的类应该如何工作吗? -
基于the documentation here 我会说你不应该像你所做的那样扩展
connect。相反,只需从您的__init__调用cx_Oracle.connect()并将连接保存为self.myConnect。 -
self.myConnect 应该返回对对象实例的引用,例如,如果没有 OOP,此代码可以工作 import cx_oracle connstr = 'user/passwd@host:port/sid' connection = cx_oracle.connect(connstr) cursor = connection.cursor() cursor.execute("SELECT * FROM table") cursor.close() connection.close()
-
我在下面更新了我的答案。
-
谢谢@beerbajay 你的方法没有继承也很好,感谢帮助