将成员函数作为函数arg传递?

时间:2012-06-07 08:08:14

标签: python sqlite select functional-programming pysqlite

我为SQLite编写了一个非常简单的select函数,但我对如何传递成员函数感到困惑......例如:.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 个答案:

答案 0 :(得分: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)())

答案 1 :(得分: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

答案 2 :(得分: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")

打印“foo”

答案 3 :(得分: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()