示例示例Python 限制参数类型的方法有以下几种:使用) 函数:
Python 限制参数类型的方法有以下几种:
1. 使用 isinstance() 函数:
isinstance() 函数可以检查变量是否属于某种特定类型,如果是则返回 True,否则返回 False。
例如:
def add(a, b):
if not (isinstance(a, int) and isinstance(b, int)):
raise TypeError('参数类型错误')
return a + b
# 调用函数
add(2, 3) # 5
add('2', 3) # TypeError: 参数类型错误
2. 使用 type() 函数:
type() 函数可以获取变量的类型,如果类型不匹配,则抛出 TypeError 异常。
例如:
def add(a, b):
if type(a) is not int or type(b) is not int:
raise TypeError('参数类型错误')
return a + b
# 调用函数
add(2, 3) # 5
add('2', 3) # TypeError: 参数类型错误
3. 使用 assert 语句:
assert 语句可以检查表达式是否为真,如果为假,则抛出 AssertionError 异常。
例如:
def add(a, b):
assert isinstance(a, int) and isinstance(b, int), '参数类型错误'
return a + b
# 调用函数
add(2, 3) # 5
add('2', 3) # AssertionError: 参数类型错误
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(43条)