|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
现有代码如下
- @fun_d(minNum=10,maxNum=20)
- def fun1(a,b):
- return a+b
- @fun_d(minNum=10,maxNum=20)
- def fun2(a,b,c):
- return a+b-c
复制代码
要求实现 fun_d 装饰器,要求:
确保使用该装饰器的方法参数都是int类型,否则抛出异常
(提示可以使用 isinstance(i,int) 判断i是否是int 类型)
参数的值在minNum 和 maxNum之间
如果参数值不符合,抛出异常
- def fun_d(minNum, maxNum):
- def outer(func):
- nonlocal minNum, maxNum
- def inner(*args):
- nonlocal minNum, maxNum, func
- for i in args:
- assert isinstance(i, int)
- assert minNum <= i <= maxNum
- return func(*args)
- return inner
- return outer
- @fun_d(minNum=10,maxNum=20)
- def fun1(a,b):
- return a+b
- fun1(10, 20)
- 30
- fun1(1, 2)
- Traceback (most recent call last):
- File "<pyshell#33>", line 1, in <module>
- fun1(1, 2)
- File "<pyshell#29>", line 8, in inner
- assert minNum <= i <= maxNum
- AssertionError
- fun1('1', '2')
- Traceback (most recent call last):
- File "<pyshell#34>", line 1, in <module>
- fun1('1', '2')
- File "<pyshell#29>", line 7, in inner
- assert isinstance(i, int)
- AssertionError
- @fun_d(minNum=10,maxNum=20)
- def fun2(a,b,c):
- return a+b-c
- fun2(1, 2, 3)
- Traceback (most recent call last):
- File "<pyshell#37>", line 1, in <module>
- fun2(1, 2, 3)
- File "<pyshell#29>", line 8, in inner
- assert minNum <= i <= maxNum
- AssertionError
- fun2('1', '2', '3')
- Traceback (most recent call last):
- File "<pyshell#38>", line 1, in <module>
- fun2('1', '2', '3')
- File "<pyshell#29>", line 7, in inner
- assert isinstance(i, int)
- AssertionError
- fun2(10, 15, 20)
- 5
复制代码
|
|