• Python——assert、isinstance的用法


    1.assert

    函数说明:

    assert语句是一种插入调试断点到程序的一种便捷的方式。
    

    使用范例

    
    assert 3 == 3
    assert 1 == True
    assert (4 == 4)
    print('-----------')
    assert (3 == 4)
    '''
    抛出AssertionError异常,后面程序不执行
    '''
    print('-----------')
    
    输出结果:

    D:UserslenovoAnaconda3python.exe F:/机器学习/生物信息学/Code/NumPy.py
    -----------
    Traceback (most recent call last):
    File "F:/机器学习/生物信息学/Code/NumPy.py", line 38, in <module>

    assert (3 == 4)
    AssertionError

    可以看到只输出一个-----------,后面的由于assert (3 == 4)抛出异常而不执行。

    2.isinstance

    函数说明 :

    当我们定义一个class的时候,我们实际上就定义了一种数据类型。我们定义的数据类型和Python自带的数据类型,比如str、list、dict没什么两样:

    判断一个变量是否是某个类型可以用isinstance()判断:

    class Student():
    def __init__(self, name, score):
    self.name = name
    self.score = score

    a = '10'
    b = 3
    c = [1, 2, 3]
    d = (1, 2, 3)
    f = Student('Eden', 99.9)

    print(isinstance(a, str)) # True
    print(isinstance(b, int)) # True
    print(isinstance(c, list)) # True
    print(isinstance(d, tuple)) # True
    print(isinstance(f, Student)) # True

  • 相关阅读:
    Linux .下Apache的安装
    从程序员到项目经理:项目管理三大目标
    linux下mysql安装
    Linux学习之常用命令
    转载:struts2拦截器
    el自定义函数库
    JAVA正则表达式小结
    JSP自定义标记
    JAVA动态代理(JDK和CGLIB)
    JAVA反射机制
  • 原文地址:https://www.cnblogs.com/yuanfang0903/p/11169471.html
Copyright © 2020-2023  润新知