我想找一个装饰师来验证论点。问题是,为了D.R.Y的利益,我希望在各种函数上使用它,这些函数具有不同的必选参数和键值参数组合。下面做这样的事情,哪种方式最像Python?我甚至可以,或者我应该为每个输入组合做一个装饰器吗?你知道吗
def my_decorator(func):
def func_wrapper(x, y, a, b, c, d):
# Check that inputs are valid
if a <= 0 or b <= 0 or c <= 0 or d <= 0:
raise Exception("a, b, c, & d must be positive")
if x < 0 or y < 0:
raise Exception("x & y must be non-negative")
return func(some_inputs)
return func_wrapper
@my_decorator
def my_fun_1(x, a=None, b=None):
return x ** (a + b)
@my_decorator
def my_fun_2(x, y, c=None):
return x + y - c
...
@my_decorator
def my_fun_n(y, b=None, d=None):
return y ** (b - d)
提前谢谢!你知道吗
我对代码留下了评论。如果清楚的话就告诉我。另外,我把它放在here下载
以下是我从装饰师那里学到的两个惊人的资源。 Amazing tutorial还有这个very easy to follow tutorial
相关问题 更多 >
编程相关推荐