对一个装饰类进行子类化

时间:2015-01-22 09:44:11

标签: python subclass decorator metaclass

你如何创建一个装饰类的子类?这是一些代码,我想我必须遗漏一些非常简单的代码

def decorator_with_args(*args, **kwargs):
    def decorator(cls):
        def wrapper(*wargs, **wkwargs):
            print("wargs", wargs, wkwargs)
            return cls(*wargs, **wkwargs)

        return wrapper

    return decorator


@decorator_with_args()
class MyClass(object):
    def __init__(self, *args, **kwargs):
        print("args", args, kwargs)


class MySubClass(MyClass):
    pass


myClass = MyClass("arg", kwarg="kwarg")

这将在编译时引发TypeError

Traceback (most recent call last):
  File "/path/to/file", line 46, in <module>
    class MySubClass(MyClass):
TypeError: function() argument 1 must be code, not str

1 个答案:

答案 0 :(得分:1)

你装饰者是错的。它应该返回一个类而不是一个函数。

def decorator_with_args(*args, **kwargs):
    def decorator(cls):
        class Wrapper(cls):
            def __init__(self, *wargs, **wkwargs):
                print(wargs, wkwargs)

        return Wrapper

    return decorator