Skip to main content

类型判断

类型判断常用

# 单个类型判断
print(isinstance(tar, int))

# 多个类型判断

使用types()

from types import *

使用isinstance()

字符串

def is_str(tar:Any) -> bool:
return isinstance(tar, str)

判断是否(filelike object)

2.x

f = open('./text', 'w')
isinstance(f, file)

3.x 在python中,类型并没有那么重要,重要的是”接口“。如果它走路像鸭子,叫声也像鸭子,我们就认为它是鸭子(起码在走路和叫声这样的行为上)。

按照这个思路我们就有了第3中判断方法:判断一个对象是否具有可调用的read,write,close方法(属性)。

# python3取消了全局的file对象
def isfilelike(f):
try:
if isinstance(getattr(f, "read"), collections.Callable) \
and isinstance(getattr(f, "write"), collections.Callable) \
and isinstance(getattr(f, "close"), collections.Callable):

return True
except AttributeError:
pass

return False

为什么用getattr而不是hasattr 这里为什么不用hasattr,而是用getattr来承担抛出AttributeError的风险呢

  • hasattr就是直接调用getattr来看是否抛出了AttributeError,如果没有抛出就返回True,否则返回False,参看这里。既然如此,我们就可以自己来完成这个工作。
  • 这样我们可以得到属性对象,然后可以用isinstance判断是否为collections.Callable的实例。两者结合,如果有该属性,并可以被调用,则返回True。

使用 assert