当前位置: 移动技术网 > IT编程>脚本编程>Python > Python中type和isinstance的使用和区别

Python中type和isinstance的使用和区别

2020年07月08日  | 移动技术网IT编程  | 我要评论

1.type(obj):用于判断一个未知对象的类型

例如:

print(type(1))  # <class 'int'>
print(type(1.1))  # <class 'float'>
print(type(True))  # <class 'bool'>
print(type(-10))  # <class 'int'>
print(type('1.1'))  # <class 'str'>
print(type(0 + 0j))  # <class 'complex'>
print(type(1,'2'))

#有报错,说明一次只能判断一个参数
Traceback (most recent call last):
  File "F:/PycharmProjects/mode_test/urllib/urllib9_error.py", line 41, in <module>
    print(type(1,'2'))
TypeError: type() takes 1 or 3 arguments

 

2.isinstance(obj1,obj2):用于在判定一个对象(obj1)是否是另一个给定类(obj2)的实例

例如:

print(isinstance(1, str))  # 返回False
a = 1
b = '1'
try:
    if isinstance(a, b):
        print('类型一样')
except Exception as e:
    print('类型不一样')

简单说就是判断a是不是属于b类型,或者可以理解为a和b的类型是不是一样

例如:

def num_test(num):
    if isinstance(num, (int, str, float, complex)): # 判断num是不是属于后面括号中的某一个类型
        print('type:', type(num).__name__)
    else:
        print('error')

num_test(1)
num_test('')

 

3.在爬虫中的简单用法

try:
    response = request.urlopen('https://httpbin.org/aaa', timeout=0.1)
    print(response.read())
except error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason, socket.timeout): # 判断e.reason是不是属于socket.timeout类型
        print('Time Out')

 

 

本文地址:https://blog.csdn.net/qq_34398519/article/details/107193249

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网