【问题标题】:Python decorator my function checkPython 装饰器我的功能检查
【发布时间】:2017-11-19 11:07:01
【问题描述】:

在我的课堂上我写了这个方法:

def ts_prep(self, test_id):
    ltouple = ()
    tab_lib = temp_library.objects.filter(main_id=test_id)
    l1 = ["Settings", ""]
    ltouple += (l1,)
    if tab_lib.count() == 0: ltouple = (l1, ["", ""])
    l = []
    for r in tab_lib.iterator():
        l.append(str(r.l_type))
        l.append(str(r.l_val))
        ltouple += (l,)
        l = []

    tslist = [x for x in ltouple]
    return tslist

如何为我的方法创建一个装饰器来执行 if tab_lib 检查,以便在所有进行相同检查的方法中添加它?

我试试

def p_decorate(func):
    def func_wrapper(test_id):
       tab_lib = temp_library.objects.filter(main_id=test_id)
        l1 = ["Settings", ""]
        ltouple += (l1,)
        if tab_lib.count() == 0: ltouple = (l1, ["", ""])
        return ltouple
   return func_wrapper

但它似乎不起作用

提前致谢

【问题讨论】:

  • 这个函数是做什么的,到目前为止你尝试了什么? SO 不是代码编写服务。

标签: python python-decorators


【解决方案1】:

首先,您的代码通常可以简化很多。这应该是等价的:

def ts_prep(self, test_id):
    tab_lib = temp_library.objects.filter(main_id=test_id)
    tslist = [["Settings", ""]]
    if tab_lib.count() == 0:
        tslist.append(["", ""])
    for r in tab_lib.iterator():
        tslist.append([str(r.l_type), str(r.l_val)])

    return tslist

要回答您的问题,您可以这样做:

import functools

def decorator(func):
    @functools.wraps(func)
    def wrapper(test_id):
        tab_lib = temp_library.objects.filter(main_id=test_id)
        tslist = [["Settings", ""]]
        if tab_lib.count() == 0:
            tslist.append(["", ""])
        return func(tab_lib, tslist)

    return wrapper

@decorator
def ts_prep(self, tab_lib, tslist):
    for r in tab_lib.iterator():
        tslist.append([str(r.l_type), str(r.l_val)])

    return tslist

【讨论】:

  • AttributeError: PrepareRst 实例没有属性'trunc'
  • @ManuelSanti 哪个代码引发了该错误,在哪一行,您自己的代码不会出现同样的错误吗?
  • 非常感谢,现在可以了!
猜你喜欢
  • 2016-08-21
  • 2018-11-23
  • 2012-03-15
  • 2020-12-10
  • 2022-01-09
  • 2018-03-05
  • 2021-12-05
  • 2023-03-28
  • 2017-05-13
相关资源
最近更新 更多