[英]What happens when IF statement is called on a list object? What method is called to determine whether is True or False?
在列表對象的實例上調用IF語句時,是否有一種魔術方法可用於評估返回的是True還是False? 例如,
a = []
b = [1, 2, 3]
if a == b: # <---- __eq__() is called and returns False
pass
if a: # <---- what is called here that returns False?
pass
是:a .__ bool__(a .__ nonzero__)嗎? 一個.__ len__?
還是完全其他的東西?
實驗時間!
class Falsy:
def __nonzero__(self):
print("it's __nonzero__")
return False
def __len__(self):
print("it's __len__")
return 0
def __bool__(self):
print("it's __bool__")
return False
def __eq__(self, other):
print("it's __eq__")
return False
if Falsy():
pass
# => it's __bool__
您可以嘗試刪除這些方法以確認對它們進行測試的優先級(對於python 3,先測試__bool__
,然后再測試__len__
)。
通過簡單地引用此文檔,@ ymonad可以在問題的注釋中提供最佳答案:
https://docs.python.org/3/library/stdtypes.html#truth-value-testing
我不希望這個。 當最佳答案甚至不是答案時,我就是無法解決。 如果可以簡單地指向文檔,那將永遠是最好的答案。
... grrrr ...嘿@ymonad,我可以給你賞金嗎,大聲笑?
從文檔https://docs.python.org/2/reference/datamodel.html#object。 非零 :
object.__nonzero__(self)
調用以實現真值測試和內置操作bool()
; 應該返回False
或True
,或者它們等於0
或1
的整數。 如果未定義此方法,則調用__len__()
(如果已定義),並且如果其結果為非零,則認為該對象為true。 如果一個類__len__()
或__nonzero__()
,則其所有實例均被視為true。
對於Python 3 https://docs.python.org/3.7/reference/datamodel.html#object。 非零 :
object.__bool__(self)
調用以實現真值測試和內置操作bool()
; 應該返回False
或True
。 如果未定義此方法,則調用__len__()
(如果已定義),並且如果其結果為非零,則認為該對象為true。 如果一個類__len__()
或__bool__()
,則其所有實例均被視為true。
嘗試:
class MyList(list):
def __bool__(self):
return True
print(bool(list([])))
if list([]):
print('This does not print')
print(bool(MyList([])))
if MyList([]):
print('This prints')
咨詢C-Python API文檔以獲取PyList ...
https://docs.python.org/3.7/c-api/list.html
...我們可以看到沒有列表特定的“ as bool”功能。 唯一可以返回“真實”值的是PyList_Size(PyObject *list)
,因此答案必須是a.__len__()
。
免責聲明:至少對於CPython。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.