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())

このメンバー関数を引数として渡すにはどうすればよいですか?

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

さて、それを動作させました:

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 に答える
0

ラムダはこれを達成できます

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 に答える