0

我为 SQLite 编写了一个非常简单的选择函数,但我对如何传递成员函数感到困惑......例如:.fetchone(), .fetchmany().

def select(cursor, select="*", table="reuters", fetch=".fetchone()", tologfile=False, logfile=""):
    if tologfile:
        logfile = open(logfile, 'w')
        logfile.write(str(cursor.execute("select * from ?;".replace('?',table).replace("select * ", "select "+select)).fetchone()))
        logfile.close()
    else: return str(cursor.execute("select * from ?;".replace('?',table).replace("select * ", "select "+select)).fetchone())

如何将此成员函数作为 arg 传递?

4

4 回答 4

3

您可以简单地传递self.fetchone以传递该函数。

如果您希望它作为默认值,只需None在函数定义中使用并添加

if whatever is None:
    whatever = self.fetchone

在函数本身。

如果您想在另一个对象上调用该方法但self继续将其作为字符串传递并使用此代码(基于您的else代码,因为该代码更短):

result = self.execute("select * from ?;".replace('?',table).replace("select * ", ("select "+attr)))
return str(getattr(result, whatever)())
于 2012-06-07T08:23:46.323 回答
2

您可以使用 getattr :

>>> class A:
...     def b(self):
...             print 'c'
... 
>>> a = A()
>>> getattr(a,'b')
<bound method A.b of <__main__.A instance at 0x7f2a24a85170>>
>>> getattr(a,'b')()
c
于 2012-06-07T08:14:08.090 回答
0

一个 lambda 可以实现这一点

class A:
  def test(self):
    print "hello world"

a = A()
func = (lambda: a.test())
func()

打印“你好世界”

这种技术也可以扩展到处理传递和转换参数

class B:
  def test(self, x):
    print x

b = B()
func = (lambda a, b : b.test(b))
func("garbage", "foo")

打印“富”

于 2012-06-07T08:16:25.593 回答
0

好的,让它工作:

import sqlite3

def select(self, attr="*", table="reuters", fetch=None, num=None, tologfile=False, logfile=""):
    if fetch is None:
        fetch=self.fetchone
    output=self.execute("select * from ?;".replace('?',table).replace("select * ", ("select "+attr+' ')))

    output=fetch(num) if num else fetch()

    if tologfile:
        logfile = open(logfile, 'w')
        logfile.write(str(output))
        logfile.close()
    else: return output

if __name__ == '__main__':    
    connection = sqlite3.connect('winkwinknudgenudgesaynomore.db')
    cursor = connection.cursor()
    cursor.execute("drop table reuters;")
    cursor.execute("create table reuters (foo text, bar text);")
    connection.commit()
    print select(cursor)
    print select(cursor, 'bar')
    print select(cursor, 'bar', fetch=cursor.fetchmany, num=5)
    cursor.close()
于 2012-06-07T08:49:39.230 回答