Python中type和isinstance的使用和区别

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')

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值