开发者

how to call methods within a class in python - TypeError problem

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("se开发者_开发问答lect 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~~


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 of cursor. You can achieve what you want without it, since cursor itself is an iterator:

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


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 its self 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜