如何在Python类中调用方法 - TypeError问题
我有一个Python类,在这个类里,我从一个方法里调用了另外两个不同的方法。一个方法能正常工作,而另一个方法却给我报了个错误:TypeError: get_doms() 需要一个参数(但我给了两个)。
def start(self,cursor):
recs = self.get_recs(cursor) # No errors here
doms = self.get_doms(cursor) # I get a TypeError here
def get_doms(self,cursor):
cursor.execute("select domain from domains")
doms = []
for i in cursor._rows:
doms.append(i[0])
return doms
def get_recs(self,cursor):
cursor.execute("select * from records")
recs = []
print cursor._rows
recs = [list(i) for i in cursor._rows]
return recs
我该怎么在同一个类的其他方法中成功调用这些方法呢?为什么一个能工作而另一个不行呢?
2 个回答
0
正如gnibbler所说,你可能在某个地方对get_doms
这个方法进行了“猴子补丁”,把它替换成了一个普通的函数,而不是一个绑定的方法(绑定的方法是指,当它在一个类里定义并且你在一个对象中访问时,它会保存自己的self
变量)。你需要在类上对这个方法进行“猴子补丁”,而不是在对象上,或者使用闭包来模拟绑定,就像在JavaScript中那样。
0
我无法重现你提到的错误。我觉得代码是没问题的。不过我建议不要使用 cursor._rows
,因为 _rows
是一个私有属性。私有属性是实现细节——未来的 cursor
版本中可能不会有这个属性。你可以不使用它来实现你想要的功能,因为 cursor
本身就是一个迭代器:
def start(self,cursor):
recs = self.get_recs(cursor)
doms = self.get_doms(cursor)
print(recs)
print(doms)
def get_doms(self,cursor):
cursor.execute("select domain from domains")
doms = [row[0] for row in cursor]
return doms
def get_recs(self,cursor):
cursor.execute("select * from records")
recs=[list(row) for row in cursor]
return recs