在python中调用另一个方法的方法

时间:2015-12-24 13:50:14

标签: python python-2.7 oop

我有很多数据库查询,我想使用一些方法来重复我的代码。我想在其他已定义的方法中调用方法,但它不起作用

我收到了这样的错误:

panel1.AutoScrollMinSize = new Size(0, panel1.Height * 2);
panel1.Paint += panel1_Paint;

void panel1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.FillEllipse(Brushes.Red, panel1.DisplayRectangle);
  e.Graphics.DrawEllipse(Pens.Green, panel1.ClientRectangle);
}

我的代码

    class Main:
  File "d.py", line 20, in Main
    for word in getUserWords("SELECT users.mail, field_data_field_what_word_are_you_looking_.field_what_word_are_you_looking__value, users.uid FROM users INNER JOIN field_data_field_what_word_are_you_looking_ ON users.uid = field_data_field_what_word_are_you_looking_.entity_id"):
TypeError: getUserWords() takes exactly 2 arguments (1 given)

2 个答案:

答案 0 :(得分:2)

更简单的例子:

class Foo(object):
   def __init__(self):
      self.foo = "bar"
   def function1(self,x):
      self.function2(x)
   def function2(self,y):
      print y

bar = Foo()
bar.function1(3) # calls function1 which in turn calls function2 which prints out 3
bar.function2(4) # calls function 2 directly.

回答你问题的主要内容:

如果你有一个类函数,它有一个第一个参数,它是按惯例自我的。如果在实例上调用该类函数(如bar.function2),则self是隐式的。如果从类中调用该类函数(如当function1调用function2时),则需要执行self.functionname,它再次隐式传递self参数。

答案 1 :(得分:0)

第一点:实现您的课程并在您的实例上调用getUserWords()

import MySQLdb as mdb
class Main:
    # snip


m = Main() 
sql = your_sql_here
for word in m.getUserWords(sql):
    print word

第二点:Main的实施存在缺陷。

Class Main:
    def connect(self):
        # this will open a new connection on each and every call

        con = mdb.connect('***', '*****', '****', '***', charset="utf8", use_unicode=True)
        return con

    def cursor(self):
        # this will 
        # 1. create a new connection on every call - which will
        #    never be closed since you don't keep a reference
        #    on it so you can close it
        # 2. create a new cursor on every call 
        cursor = self.connect.cursor()

        # and this one will raise a TypeError 
        # => "'Cursor' object is not callable"
        return cursor() 
        # so I assume your real code is :
        return cursor

    def getUserWords(self, sql):
        # assigning sql to self is totally useless here
        self.sql = sql

        # so (assuming self.cursor returns the cursor and not 
        # the call to the cursor), this will:
        # - open a new connection
        # - create a new cursor
        # - execute the sql
        # - and discards eveything (cursor and connection)
        #   without closing them 
        self.cursor.execute(self.sql)

        # now we 
        # - open a second connection (without closing the first)
        # - create a second cursor
        # - call .fetchall() on it, which will raise a  
        #   _mysql_exceptions.ProgrammingError
        data = self.cursor.fetchall()

        # we're not making it until this part because of
        # the above error, but if we did, this would:
        # - create yet a third connection and call .commit()
        #   on it - which in this case would mainly be a no-op
        #   since we have nothing to commit
        self.connect.commit()

        # and finally create a fourth connection and close it
        # immediatly - note that this will be the only one that
        # gets closed <g>
        self.connect.close()
        return data

您的代码的固定版本可能如下所示:

import MySQLdb as mdb

class Main(object):

    def __init__(self, connection_data):
        self._connection_data = connection_data.copy()
        self._connection_data.update(charset="utf8", use_unicode=True)
        self._db = None

    @property
    def db(self):
        if self._db is None:
            self._db = mdb.connect(**self._connection_data)
        return self._db

    def cursor(self):
        return self.db.cursor()

    def execute(self, sql):
        cursor = self.cursor()
        cursor.execute(self.sql)
        for row in cursor:
            yield row
        self.db.commit()
        cursor.close() 


    def __del__(self):
        try:
            self._db.close()
        except:
            # either it's not set or it's already closed
            pass


m = Main(db="***", user="***", passwd="***")
for w in m.getUserWords(your_sql_here):
    print w