【问题标题】:Python wrapper preventing function call?Python包装器阻止函数调用?
【发布时间】:2012-06-10 03:05:00
【问题描述】:

我已经编写了一堆帮助函数来包装常用函数,例如插入和选择。下面包含的只是其中一个包装器......我似乎无法弄清楚它为什么不起作用。

我怀疑这与包装器有关:

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

【问题讨论】:

    标签: python sqlite cursor wrapper


    【解决方案1】:

    您的柜台装饰器从未真正调用 func。

    试试

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

    【讨论】:

    • 谢谢,正是我想要的:)。将在 10 分钟内接受 [当它允许时!]
    猜你喜欢
    • 2018-03-07
    • 2017-09-13
    • 1970-01-01
    • 2012-06-18
    • 2017-12-11
    • 2015-04-13
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多