如何在python中调用类中的方法 - TypeError问题
我有一个 python 类,在该类中我从其他方法之一调用 2 个不同的方法。一种有效,另一种给我一个 TypeError: get_doms() gets正好 1 个参数(给定 2 个):
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
如何从同一类中的其他方法成功调用类中的方法?为什么一个有效而另一个无效? ~~谢谢~~
I have a python class and within the class I call 2 different methods from one of the other methods. One works and one gives me a TypeError: get_doms() takes exactly 1 argument (2 given) :
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
How do I successfully call methods within my class from other methods within the same class? Why does one work and the other not?
~~thanks~~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我无法重现你提到的错误。我认为代码没问题。但我建议不要使用
cursor._rows
因为_rows
属性是私有属性。私有属性是一个实现细节——不保证它们在cursor
的未来版本中存在。没有它你也可以实现你想要的,因为cursor
本身就是一个迭代器:I can't reproduce the error you mention. I think the code is okay. But I suggest do not use
cursor._rows
because the_rows
attribute is a private attribute. Private attributes are an implementation detail -- they are not guaranteed to be there in future versions ofcursor
. You can achieve what you want without it, sincecursor
itself is an iterator:正如 gnibbler 所说,您可能会对
get_doms
方法进行猴子修补,并将其替换为普通函数,而不是绑定方法(方法被绑定,也就是说,它保存其self 变量,当它在类中定义并且您在对象中访问它时)。您需要在类上(而不是在对象上)对该方法进行猴子修补,或者使用闭包来模拟绑定,就像在 js 中一样。
As gnibbler said, you probably monkey-patch the
get_doms
method somewhere and replace it with a normal function, instead of a bound method (method gets bound, that is, it saves itsself
variable, when it's defined in a class and you access it in an object). You need to either monkey-patch that method on the class, not on the object, or use a closure to emulate binding, just like in js.