[英]__iter__: int and str vs list and tuple
some_obj = "scalar"
list_like = "__iter__" in dir(some_obj) # Py2: False; Py3: True
我在 python 2 中使用它来区分“非迭代”( str
、 int
、 bool
、 None
)和迭代( list
、 dict
、 tuples
)。
这不再适用于 python3,因为str
现在具有__iter__
属性( 为什么 python 2.7 中的字符串没有“__iter__”属性,但 python 3.7 中的字符串具有“__iter__”属性)。
好吧,通常最好不要将str
视为类似列表。 那么有没有比"__iter__" in dir(some_obj) and not type(some_obj)==str
或这个问题中的所有案例检查? 我是否会错过其他有争议的对象,例如str
?
我不确定使用__iter__
来检查类型是否好,这个有一个更好的选择, Iterable
类型。
分组是你自己的意见,所以我认为最简单的方法是设置黑名单...
try:
from collections.abc import Iterable # py3
except ImportError:
from collections import Iterable #py2
def check(arg):
if not isinstance(arg, Iterable):
return False
elif isinstance(arg, (str, bytes)):
return False
else:
return True
编辑:为了不让我的回答引起混淆,我在这里引用了文档。
class collections.abc.Iterable
ABC 用于提供iter () 方法的类。
检查 isinstance(obj, Iterable) 会检测注册为 Iterable 或具有iter () 方法的类,但不会检测使用getitem () 方法迭代的类。 确定 object 是否可迭代的唯一可靠方法是调用 iter(obj) 。
这适用于 2 和 3。 str
当然是可迭代的。
n1 = 1
s1 = 'abc'
objs = [n1, s1]
for o in objs:
try:
iter(o)
except TypeError:
print(o, 'is not Iterable!')
else:
print(o, 'is Iterable!')
Output:
1 is not Iterable!
abc is Iterable!
报价取自这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.