子class装饰class
Subclassing a decorated class
你会如何分class 装饰class?这是一些代码,我想我一定遗漏了一些非常简单的东西
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
你的装饰器错了。它应该返回 class 而不是函数。
def decorator_with_args(*args, **kwargs):
def decorator(cls):
class Wrapper(cls):
def __init__(self, *wargs, **wkwargs):
print(wargs, wkwargs)
return Wrapper
return decorator
你会如何分class 装饰class?这是一些代码,我想我一定遗漏了一些非常简单的东西
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
你的装饰器错了。它应该返回 class 而不是函数。
def decorator_with_args(*args, **kwargs):
def decorator(cls):
class Wrapper(cls):
def __init__(self, *wargs, **wkwargs):
print(wargs, wkwargs)
return Wrapper
return decorator