使用isinstance()函数,判断输入的函数是否为已知的类型。raise() 引发异常。

语法:isinstance(object,type)

参数:object是对象,type是直接或间接类型名,或者基本类型组成的元组,(A type or a class, or a tuple of types and/or classes)。

如果规定的object是规定的类型,就会返回True。

如果参数类型为元组,object的类型是元组中的其中一种,则返回True。

type类型可以是:int,float,bool,complex(复数),str(字符串),list,dict(字典),set(集合),tuple(元组)

1 x = isintance("hello", (float, int, str, list, dict, tuple))
2 print (x)
3 #return True

raise用于引发异常

(raise 提出,exception不赞同)

x = -1
if x<0:
     raise Exception("Sorry,no numbers blew zero")  

综合:

例如:可以判断输入的函数参数是否为指定类型。如果输入的函数参数错误,就会指出错误。

1 def my_abs(x):
2     if not isinstance(x,(int, float)):
3         raise TypeError('bad operand type!')
4     if x >= 0;
5         return x
6     else:
7         return -x
my_abs('sss')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in my_abs
TypeError: bad operand type!
my_abs('-99')
99
 
原文地址:https://www.cnblogs.com/3lina/p/10299454.html