为了更好地解释,请考虑这个简单的类型检查器函数:
from collections import Iterable
def typecheck(obj):
return not isinstance(obj, str) and isinstance(obj, Iterable)
如果obj
是str
以外的可iterable类型,则返回True
。但是,如果obj
是str
或不可iterable类型,则返回False
。
有什么方法可以更有效地执行类型检查吗?我的意思是,检查一下obj
的类型,看看它是否不是str
,然后再次检查它是否是可接受的,这似乎有点多余。
我想列出除str
之外的所有其他iterable类型,如下所示:
return isinstance(obj, (list, tuple, dict,...))
但问题是,这种方法将丢失未显式列出的任何其他iterable类型。
那么…有什么更好的方法或者我在函数中给出的方法是最有效的吗?
我用这段代码检查它,它在Python 2和Python 3中运行良好
在python 2.x中,检查
__iter__
属性是有帮助的(尽管并不总是明智的),因为iterables应该有这个属性,但是字符串没有。缺点是
__iter__
不是一种真正的python方法:例如,有些对象可能实现__getitem__
,但不是__iter__
。在Python 3.x中,strings得到了
__iter__
属性,从而破坏了这个方法。您所列出的方法是Python 3.x中我所知道的最有效的、真正的Python方法:
有一种更快(更有效)的方法,就是像Python 2.x那样检查
__iter__
,然后检查str
。这与Python2.x中的警告相同,但速度要快得多。
相关问题 更多 >
编程相关推荐