接受多个输入的装饰器就像{{link1:
dataclasses
装饰器}}。
在这个例子中,
dataclass
接受三种语法:
@dataclass
class C:
...
@dataclass()
class C:
...
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
match_args=True, kw_only=False, slots=False, weakref_slot=False)
class C:
...
在创建具有相同行为的装饰器时,您可以使用以下代码:
import inspect
def customdecorator(*args, **kwargs):
def decorator(func):
print('input decorator:', args, kwargs)
def __wrapper(*func_args, **func_kwargs):
print('input decorator inside function:', args, kwargs)
print('input function:', func_args, func_kwargs)
result = func(*func_args, **func_kwargs)
return result
return __wrapper
print('input root:', args, kwargs)
if len(kwargs) > 0:
return decorator
if len(args) == 0:
return decorator
if len(args) == 1:
return decorator(args[0])
@customdecorator
def example1():
print("Function without call")
@customdecorator()
def example2():
print("Function without arguments")
@customdecorator(arg1="value1", arg2="value2")
def example3(arg2):
print(f"Function with arguments: {arg2}")
example1()
example2()
example3(arg2="ex2")
在你的情况下,这将是
def myDecorator(*args, **kwargs):
def decorator(func):
def __wrapper(*func_args, **func_kwargs):
test_func = kwargs.get('test_func', None)
logIt = kwargs.get('logIt', None)
if logIt:
print("Calling Function: " + test_func.__name__)
result = func(*func_args, **func_kwargs)
return result
return __wrapper
if len(kwargs) > 0:
return decorator
if len(args) == 0:
return decorator
if len(args) == 1:
return decorator(args[0])
@myDecorator(logIt=False)
def someFunc():
print('Hello')
someFunc()
注意事项是:
- 可选参数必须使用关键字参数。
- 默认值通过
kwargs.get(..., ...)
输入。