内部函数isinstance说明

 isinstance说明如下:
  isinstance(object, class-or-type-or-tuple) -> bool  
  Return whether an object is an instance of a class or of a subclass thereof.
  With a type as second argument, return whether that is the object's type.
  The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A)
  or isinstance(x, B) or ... (etc.).
其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。
若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。
 
 
 

传入了不恰当的参数时,内置函数abs会检查出参数错误,而我们定义的my_abs没有参数检查,所以,这个函数定义不够完善。

让我们修改一下my_abs的定义,对参数类型做检查,只允许整数和浮点数类型的参数。数据类型检查可以用内置函数isinstance实现:

def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x

添加了参数检查后,如果传入错误的参数类型,函数就可以抛出一个错误:

>>> my_abs('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in my_abs
TypeError: bad operand type

posted on 2014-12-18 15:45  网络小蚂蚁  阅读(436)  评论(0)    收藏  举报

导航