Python2
Python2 有一種比較可靠的方式就是判斷對象的類型是否是file
類型。因此可以使用type
函數或者isinstance
函數實現。
type
當然type函數無法對繼承得來的子類起作用
>>> f = open('./text', 'w')
>>> type(f)
<type 'file'>
>>> type(f) == file
True
>>> class MyFile(file):
... pass
...
>>> mf = MyFile('./text')
>>> type(mf)
<class '__main__.MyFile'>
>>> type(mf) == file
False
isinstance
isinstancne
是推薦的判斷類型時方法,通常情況下都應該選擇此方法。isinstance
也可以對子類起作用。
>>> f = open('./text', 'w')
>>> isinstance(f, file)
True
>>> class MyFile(file):
... pass
...
>>> mf = MyFile('./text')
>>> isinstance(mf, file)
True
Python3
在 Python3 中,官方取消了file
這一對象類型,使得 python2 中的判斷方法無法在 Python3 中使用。
因此在 Python3 中只能通過鴨子類型的概念判斷對象是否實現了可調用的``read
, write
, close
方法, 來判斷對象是否是一個文件對象了。
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
當然這個方法也可以在 python2 中使用