gpt4 book ai didi

python - 使用错误的输入类型调用函数时打印 "Wrong Type"- Python

转载 作者:行者123 更新时间:2023-12-01 09:03:30 25 4
gpt4 key购买 nike

我试图在函数中输入错误类型的数据时显示错误消息。在这种情况下,我只是在调用函数时尝试接受 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)

最佳答案

如果您使用的是 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'>

关于python - 使用错误的输入类型调用函数时打印 "Wrong Type"- Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com