[英]Decorator and error function() argument 1 must be code, not str
I have next code 我有下一个代码
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
This is works fine: 这很好用:
@timer_dec
class A(object):
pass
But this is not working: 但这不起作用:
@timer_dec
class A(object):
pass
class B(A):
pass
TypeError: Error when calling the metaclass bases function() argument 1 must be code, not str
TypeError:调用元类base函数时出错()参数1必须是代码,而不是str
Python version is 2.7
Python版本是2.7
You seem to be using a function decorator as a class decorator. 您似乎使用函数装饰器作为类装饰器。
@timer_dec
class A(object):
pass
is equivalent to 相当于
class A(object):
pass
A = timer_dec(A)
Because timer_dec
returns a function, A
is now a function. 因为
timer_dec
返回一个函数,所以A
现在是一个函数。
You can create a class decorator that applies a function decorator to all methods of the class. 您可以创建一个类装饰器,将函数装饰器应用于该类的所有方法。 See here for an example: Alex Martelli's answer to Applying python decorators to methods in a class
请参阅此处的示例: Alex Martelli将Python python装饰器应用于类中的方法的答案
Your decorator is returning a function. 你的装饰者正在返回一个函数。 Thus, after the decorator call, the name "A" is bound to a function, not a class.
因此,在装饰器调用之后,名称“A”绑定到函数,而不是类。 Then, you try to inherit B from the function A, which is illegal.
然后,您尝试从函数A继承B,这是非法的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.