Mefine 发表于 2022-11-22 10:39:58

装饰器流程判断

现有代码如下
@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之间
如果参数值不符合,抛出异常

tommyyu 发表于 2022-11-22 10:57:43

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

Mefine 发表于 2022-11-22 11:53:25

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

@fun_d(minNum=10,maxNum=20)
def fun2(a,b,c):
    return a+b-c

f = fun1(10,20),fun2(10,20,15)

jackz007 发表于 2022-11-22 11:57:59

def fun_d(minNum = 10 , maxNum = 20):
    def outer(func):
      def inner(* args):
            for x in args :
                if not type(x) == int or x < minNum or x > maxNum :
                  return str(args) + ' : parameter type or value error.'
            else :
                return func(* args)
      return inner
    return outer

@fun_d(10 , 20)
def fun1(a,b):
    return a+b

@fun_d(10 , 20)
def fun2(a,b,c):
    return a+b-c

print(fun1(15 , 16))               # 合格
print(fun1(3 , 15))                # 不合格
print(fun2(12 , 13 , 15))          # 合格
print(fun2(2 , 3 , 5))             # 不合格
print(fun1('abc' , 123))         # 不合格
print(fun2('abc' , 'bcd' , 123))   # 不合格

Mefine 发表于 2022-11-22 12:05:44

jackz007 发表于 2022-11-22 11:57


看起来确实更简洁一些,手动最佳~{:10_256:}
页: [1]
查看完整版本: 装饰器流程判断