gpt4 book ai didi

python - 在 Python 中,如何确定对象是否可迭代?

转载 作者:IT老高 更新时间:2023-10-28 11:58:24 24 4
gpt4 key购买 nike

有没有类似isiterable的方法?到目前为止我找到的唯一解决方案是调用

hasattr(myObj, '__iter__')

但我不确定这是多么简单。

最佳答案

  1. 检查 __iter__ 适用于序列类型,但会失败,例如Python 2 中的字符串。我也想知道正确的答案,在那之前,这是一种可能性(也适用于字符串):

     try:
    some_object_iterator = iter(some_object)
    except TypeError as te:
    print(some_object, 'is not iterable')

iter 内置检查 __iter__ 方法,如果是字符串,则检查 __getitem__ 方法。

  1. 另一种通用的pythonic方法是假设一个可迭代的,然后如果它不适用于给定的对象,则优雅地失败。 Python 词汇表:

Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.

...

try:
_ = (e for e in my_object)
except TypeError:
print my_object, 'is not iterable'
  1. collections模块提供了一些抽象基类,允许询问类或实例是否提供特定功能,例如:

     from collections.abc import Iterable

    if isinstance(e, Iterable):
    # e is iterable

但是,这不会检查可通过 __getitem__ 迭代的类。

关于python - 在 Python 中,如何确定对象是否可迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1952464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com