为了更好地解释,请考虑这种简单的类型检查功能:
from collections import Iterable
def typecheck(obj):
return not isinstance(obj, str) and isinstance(obj, Iterable)
如果 obj
是一个可迭代的类型 str
,它回来了 True
。但是,如果 obj
是一个 str
或者是不可迭代的类型,它返回 False
。
有没有办法更有效地执行类型检查?我的意思是,检查类型似乎有点多余 obj
曾经看过它是不是一个 str
然后检查一下 再次 看看它是否可迭代。
我想除了列出其他所有可迭代类型 str
喜欢这个:
return isinstance(obj, (list, tuple, dict,...))
但问题是该方法将错过任何未明确列出的其他可迭代类型。
所以...有什么更好的,或者我在函数中给出的方法效率最高?
在 python 2.x,检查 __iter__
属性是有用的(虽然并不总是明智的),因为iterables应该具有此属性,但字符串不具有此属性。
def typecheck(obj): return hasattr(myObj, '__iter__')
不好的是那个 __iter__
并不是真正的Pythonic方法:有些对象可能会实现 __getitem__
但不是 __iter__
例如。
在 Python 3.x,字符串得到了 __iter__
属性,破坏了这个方法。
您列出的方法是我在Python 3.x中知道的最有效的Pythonic方法:
def typecheck(obj): return not isinstance(obj, str) and isinstance(obj, Iterable)
有一种更快(更有效)的方式,即检查 __iter__
喜欢在Python 2.x中,然后再检查 str
。
def typecheck(obj): return hasattr(obj, '__iter__') and not isinstance(obj, str)
这与Python 2.x中的注意事项相同,但速度要快得多。
我用这个代码检查它,它适用于Python 2和3
from __future__ import unicode_literals
import types
import collections
var = ["a", "b", "c"]
if isinstance(var, collections.Iterable) and \
not isinstance(var, types.StringTypes):
return var