Python中的装饰器。如何检查参数类型

2024-09-26 22:45:02 发布

您现在位置:Python中文网/ 问答频道 /正文

def args_typecheck(func):    
    def wrapper(type):
        def inner(*args):
            if not all(map(lambda x: isinstance(x, type), args)):
                raise TypeError
            return func(*args)
        return inner
    return wrapper

@args_typecheck(str)
def seq(*args):
    return reduce(operator.eq, args)

我尝试使用修饰符检查输入参数类型。但它不起作用。在

错误:

if not all(map(lambda x: isinstance(x, type), args)): E TypeError: isinstance() arg 2 must be a type or tuple of types


Tags: lambdamapreturnifdeftypenotargs
1条回答
网友
1楼 · 发布于 2024-09-26 22:45:02

您的装饰函数签名颠倒了:wrapper应采用原始包装的函数,args_typecheck应采用要检查的类型:

def args_typecheck(type):
   def wrapper(func):
      def inner(*args):
        if not all(map(lambda x: isinstance(x, type), args)):
            raise TypeError
        return func(*args)
      return inner
   return wrapper

@args_typecheck(str)
def seq(*args):
  return reduce(operator.eq, args)

相关问题 更多 >

    热门问题