【问题标题】:Printing "Wrong Type" when calling a function with the wrong input type - Python调用具有错误输入类型的函数时打印“错误类型” - Python
【发布时间】:2018-09-11 02:34:24
【问题描述】:

我试图在错误类型的数据输入到函数时显示错误消息。在这种情况下,我只是在调用函数时尝试接受intfloat。在函数中输入str 应该会返回错误消息

def isPrime(i):

    if not (type(i)==float or type(i)==int):
        print("Input wrong type")
        return None

    i = abs(int(i))

    if i == 2 or i == 1: 
        return True    

    if not i & 1: 
        return False

    for x in range(3, int(i**0.5) + 1, 2):
        if i % x == 0:
            return False

    return True

# Wanting the code to return an error
isPrime(bob) 

【问题讨论】:

  • 问题是什么?你的函数表现如何?
  • bob 不是一个字符串……它什么都不是,因为你还没有初始化它。试试isPrime('bob')
  • 你不应该使用type() == typename;一般来说,您应该改用isinstance(input, type)。要给出错误,您想raise 错误。在这种情况下,由于类型错误,您可以使用raise TypeError 而不是return None。您还可以使用特定的错误消息引发错误,如下所示:raise TypeError('Input must be a float or int')
  • 我看不出你的代码有什么问题。您将bob 设置为什么?运行代码时会得到什么输出?

标签: python python-3.x


【解决方案1】:

如果您使用的是 Python 3.5+,则可以使用带有以下装饰器的类型提示(我改编自 @MartijnPieters 的 typeconversion decorator)来强制执行类型提示:

import functools
import inspect

def enforce_types(f):
    sig = inspect.signature(f)
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        bound = sig.bind(*args, **kwargs)
        bound.apply_defaults()
        args = bound.arguments
        for param in sig.parameters.values():
            if param.annotation is not param.empty and not isinstance(args[param.name], param.annotation):
                raise TypeError("Parameter '%s' must be an instance of %s" % (param.name, param.annotation))
        result = f(*bound.args, **bound.kwargs)
        if sig.return_annotation is not sig.empty and not isinstance(result, sig.return_annotation):
            raise TypeError("Returning value of function '%s' must be an instance of %s" % (f.__name__, sig.return_annotation))
        return result
    return wrapper

@enforce_types
def isPrime(i: float) -> bool:
    i = abs(int(i))
    if i == 2 or i == 1: 
        return True    
    if not i & 1: 
        return False
    for x in range(3, int(i**0.5) + 1, 2):
        if i % x == 0:
            return False
    return True

这样:

print(isPrime(1))
print(isPrime(1.0))

都会输出True,但是:

print(isPrime('one'))

会引发以下异常:

TypeError: Parameter 'i' must be an instance of <class 'float'>

【讨论】:

  • 很酷的装饰器!我认为它应该是标准库的一部分。
【解决方案2】:

所以:

if not (type(i)==float or type(i)==int):
    print("Input wrong type")
    return None

可以简化为:

if not isinstance(i,(float,int)):
    print("Input wrong type")
    return None

然后做错误信息:

if not isinstance(i,(float,int)):
    raise TypeError('Your Text here') #You can do any error i do `TypeError` just for now.

然后创建自己的错误信息:

class MyError(Exception):
    pass

那么这里:

if not isinstance(i,(float,int)):
    raise MyError('Your Text here')

但我更喜欢使用TypeError 来做错误

【讨论】:

  • raiseing 之后不需要return,否则,简明扼要!
  • @AlexanderReynolds 哦,是的,这是正确的,非常感谢
  • @AlexanderReynolds 完成!
  • 保持类型错误。这就是它的用途。无需激增自定义错误类型。另外,如果您提出,请不要打扰打印。只需将打印消息作为错误消息即可。
  • @MadPhysicist 是的,没错,已编辑,但只是为了让 OP 知道如何创建错误消息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 2012-09-27
相关资源
最近更新 更多