Python封装阻止函数调用? [英] Python wrapper preventing function call?
本文介绍了Python封装阻止函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一堆帮助函数来包装常用的函数,如插入和选择。下面包含的只是其中一个封装...我似乎不明白为什么它不工作。
I've written a bunch of helper functions to wrap common functions such as insert and select. Included below is just one of those wrappers... which I can't seem to figure out why it isn't working.
我怀疑这是与包装器:
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()
推荐答案
>调用 func。
Your counter decorator never actually calls func.
尝试
def counter(func):
def wrapper(*args, **kwargs):
wrapper.count += 1
return func(*args, **kwargs) # <- this line is important!!
wrapper.count = 0
return wrapper
这篇关于Python封装阻止函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文