4

docsから、all次と同等です:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

では、なぜこの出力が得られるのでしょうか。

# expecting: False

$ python -c "print( all( (isinstance('foo', int), int('foo')) ) )"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

いつ:

# expecting: False

$ python -c "print( isinstance('foo', int) )"
False
4

4 に答える 4

5

引数は、関数を呼び出す前に評価されます。この場合、最初に に渡すタプルを作成する必要がありますall

allそれらをチェックする機会がなかったので、その前に例外がスローされました。

>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
于 2013-06-28T14:21:00.127 に答える
2

あなたの直感allは正しいです。レイジー シーケンスを設定するには、もう少し努力する必要があります。例えば:

def lazy():
    yield isinstance("foo", int)   # False
    yield int("foo")               # raises an error, but we won't get here

>>> all(lazy())
False
>>> list(lazy())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in lazy
ValueError: invalid literal for int() with base 10: 'foo'
于 2013-06-28T14:59:36.030 に答える
1

最初の条件の後に評価を停止したいのが、False特に型チェックを実行することである場合は、次のようなものがうまく機能します。

if not isinstance(other, MyClass):
    return False
else:
    return all((self.attr1 == other.attr2,
                self.attr2 == other.attr2)) # etc.

@catchmeifyoutry の簡略版:

return isinstance(other, MyClass) and all((self.attr1 == other.attr2,
                                           self.attr2 == other.attr2)) # etc.
于 2013-06-28T14:33:24.607 に答える