【发布时间】:2013-03-23 16:09:28
【问题描述】:
我想使用装饰器对派生类做一些事情(例如注册类或其他东西)。这是我的代码:
from functools import wraps
class Basic(object):
def __init__(self):
print "Basic::init"
def myDeco(name):
# define the decorator function that acts on the actual class definition
def __decorator(myclass):
# do something here with the information
print name, myclass
# do the wrapping of the class
@wraps(myclass)
def __wrapper(*args, **kwargs):
return myclass( *args, **kwargs)
# return the actual wrapper here
return __wrapper
# return the decorator to act on the class definition
return __decorator
@myDeco("test")
class Derived(Basic):
def __init__(self):
super(Derived, self).__init__()
print "Derived::init"
instance = Derived()
这给出了以下错误:
TypeError: must be type, not function
当Derived 中的super 方法被调用时。我假设变量Derived 不再是type,而是函数__decorator 实际上。
我需要如何更改装饰器(并且只有装饰器)才能解决此问题?
【问题讨论】:
-
装饰器内的装饰器 - 它自找麻烦...
-
@JakubM.: 不,这个函数是一个装饰器工厂。这是常见的做法。
-
@wraps在myDeco内?对我来说看起来很奇怪 -
IMO,在这种情况下,
__wrapper毫无意义。对于__decorator,可以直接返回myclass。
标签: python python-2.7 inheritance decorator python-decorators