python bool类型return_Python bool()函数可以为无效参数引发异常吗?
當(dāng)__bool__沒有返回True或False時,bool會抱怨.
>>> class BoolFail:
... def __bool__(self):
... return 'bogus'
...
>>> bool(BoolFail())
[...]
TypeError: __bool__ should return bool, returned str
但是,沒有內(nèi)置類型這種瘋狂.
DSM做了一個非常有價值的評論:流行的numpy庫有bool會產(chǎn)生錯誤的例子.
>>> import numpy as np
>>> a = np.array([[1],[2]])
>>> bool(a)
[...]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Standard, near-universal stdlib example for things like this: a weakref.proxy to a dead object will raise a ReferenceError for almost any operation, including bool.
>>> import weakref
>>> class Foo:
... pass
...
>>> bool(weakref.proxy(Foo()))
[...]
ReferenceError: weakly-referenced object no longer exists
這不是bool獨有的,任何使用其dead參數(shù)的函數(shù)都可能拋出此錯誤,例如myfunc = lambda x:print(x).
總結(jié)
以上是生活随笔為你收集整理的python bool类型return_Python bool()函数可以为无效参数引发异常吗?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPPO 刘作虎:Find X6 系列大
- 下一篇: 金山办公 2022 年订阅收入 27.4