【发布时间】:2019-12-07 10:53:35
【问题描述】:
我正在尝试创建一个装饰器,它将向包装类__init__ 方法注入一些功能。这是有效的。
class Decorator:
def __init__(self, arg):
print(arg)
self.arg = arg
def __call__(self, cls):
print(cls)
class Wrapped(cls):
def __init__(self, first_arg, second_arg, **kwargs):
cls.__init__(self, first_arg, second_arg, **kwargs)
print('in wrapped init', self.variable)
return Wrapped
@Decorator('random_string')
class TestClass:
def __init__(self, first_arg, second_arg, **kwargs):
self.variable = 10
print('TestClass init')
test = TestClass(first_arg='one', second_arg='two')
并产生
random_string
<class '__main__.TestClass'>
TestClass init
in wrapped init 10
由于一些神秘的原因,删除装饰器参数后代码不再工作(在这种情况下是随机字符串)
@Decorator
class TestClass:
def __init__(self, first_arg, second_arg, **kwargs):
self.variable = 10
print('TestClass init')
输出:
Traceback (most recent call last):
File "/home/python_examples/test_decorators.py", line 24, in <module>
test = TestClass(first_arg='one', second_arg='two')
<class '__main__.TestClass'>
TypeError: __call__() got an unexpected keyword argument 'first_arg'
两个问题:
- 这是一种众所周知且有效的装饰类的方法吗?
- 为什么从未使用过的“random_string”参数至关重要?
【问题讨论】:
标签: python class python-decorators