2012-06-10 415 views
0

我已經寫了一堆幫助函數來包裝常見的功能,如插入和選擇。下面包含的只是其中的一個包裝......我似乎無法弄清楚它爲什麼不起作用。防止函數調用的Python包裝?

我懷疑這是值得做的包裝:

from collections import Mapping 
import sqlite3 

def counter(func): 
    def wrapper(*args, **kwargs): 
     wrapper.count = wrapper.count + 1 
    wrapper.count = 0 
    return wrapper 

@counter 
def insert(val, cursor, table="reuters_word_list", logfile="queries.log"): 
    if val: 
     if isinstance(val, (basestring, Mapping)): 
      val='\"'+val+'\"' 
     query = ("insert into %s values (?);" % 'tablename', val) 
     if logfile: 
      to_logfile(query + '\n', logfile) 
     cursor.execute(query) 

if __name__ == '__main__': 
    connection = sqlite3.connect('andthensome.db') 
    cursor = connection.cursor() 
    cursor.execute("create table wordlist (word text);") 
    insert("foo", cursor) 
    connection.commit() 
    cursor.execute("select * from wordlist;") 
    print cursor.fetchall() 
    cursor.close() 

回答

6

你的櫃檯裝飾從未真正電話 FUNC。

嘗試

def counter(func): 
    def wrapper(*args, **kwargs): 
     wrapper.count += 1 
     return func(*args, **kwargs)  # <- this line is important!! 
    wrapper.count = 0 
    return wrapper 
+0

謝謝,我想正是:)。將在10分鐘內接受[何時允許我!] – user1438003