【问题标题】:Decorator and error function() argument 1 must be code, not str装饰器和错误函数()参数 1 必须是代码,而不是 str
【发布时间】:2013-02-15 19:41:24
【问题描述】:

我有下一个代码

def timer_dec(f):
    def wrapper(*args, **kwargs):
        t = time.time()
        args[0].debug('<{}> start'.format(f.__name__))
        res = f(*args, **kwargs)
        args[0].debug('<{}> finish'.format(f.__name__))
        args[0].debug("Working time for function <%s>: %f" % (f.__name__, time.time() - t))
        return  res

    return wrapper

这很好用:

@timer_dec
class A(object):
  pass

但这不起作用:

@timer_dec
class A(object):
  pass

class B(A):
  pass

TypeError:调用元类基函数()参数时出错 1 必须是代码,而不是 str

Python 版本是 2.7

【问题讨论】:

  • 你能举一个类装饰器的例子吗?

标签: python decorator


【解决方案1】:

您似乎将函数装饰器用作类装饰器。

@timer_dec
class A(object):
  pass

等价于

class A(object):
  pass
A = timer_dec(A)

因为timer_dec 返回一个函数,所以A 现在是一个函数。


您可以创建一个类装饰器,将函数装饰器应用于类的所有方法。示例见此处:Alex Martelli's answer to Applying python decorators to methods in a class

【讨论】:

  • Python 3 也是如此,它给出了同样无用的错误消息。
【解决方案2】:

你的装饰器正在返回一个函数。因此,在装饰器调用之后,名称“A”被绑定到一个函数,而不是一个类。 然后,您尝试从函数 A 继承 B,这是非法的。

【讨论】:

    猜你喜欢
    • 2019-10-29
    • 2022-11-21
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2020-04-02
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多