在python中调用另一个方法

2024-10-01 09:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我得到了这样的错误:

    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)

我的代码

^{pr2}$

Tags: 方法代码inyou数据库fielduiddata
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.

回答您问题的主要要点:

如果你有一个类函数,它有一个按惯例self的第一个参数。如果在实例上调用该类函数(如酒吧功能2)自我是内隐的。如果从类内部调用该类函数(就像function1调用function2时一样),则需要执行以下操作self.functionname,它再次隐式传递自变量。在

第一点:实例化类并在实例上调用getUserWords()

import MySQLdb as mdb
class Main:
    # snip


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

第二点:Main的实现有缺陷。在

^{2}$

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

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

相关问题 更多 >