2012-06-07 46 views
0

我寫了一個非常簡單的SQLite選擇函數,但我很困惑如何傳遞成員函數......例如:.fetchone(),.fetchmany()將成員函數作爲函數arg傳遞?

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?

回答

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

一個lambda可以做到這一點

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

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

輸出 「Hello World」

這種技術也可以擴展到處理的傳球和轉換論據

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

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

打印「foo」

+0

或者,你可以使用'func = a.test'。 lambda是不必要的。 – Ben

3

您可以簡單地通過self.fetchone來傳遞該函數。

如果你想它作爲默認值只是在函數定義中使用None和函數本身添加

if whatever is None: 
    whatever = self.fetchone 

如果你想調用的方法上的另一個對象,但self一直將它作爲一個字符串,並使用此代碼(根據您的else代碼,因爲一個人的短):

+0

謝謝,但我無法得到那個工作:http://ideone.com/Rc5aY – user1438003

+0

啊,你想調用該方法對查詢內的對象..誤解了你的問題 – ThiefMaster

+0

沒有後顧之憂,期待閱讀修改後的答案:) – user1438003

相關問題