我創建了一個包含__bool__
特殊方法的自定義物件,如下所示:
class CustomObject:
def __init__(self, value):
self.value = value
def __bool__(self):
print("This is from the __bool__ method")
return True
obj = CustomObject(10)
if obj:
print("Inside if")
輸出:
This is from the __bool__ method
Inside if
if
陳述句呼叫__bool__
特殊方法。但是,在下面的代碼中,自定義模型不包含__bool__
特殊方法,但if
陳述句的條件仍然為 True:
class CustomObject:
def __init__(self, value):
self.value = value
obj = CustomObject(10)
print(dir(obj))
if obj:
print("Inside if")
輸出:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'value']
Inside if
所以我的問題是,if
陳述句呼叫了上部分中的哪些特殊方法?
uj5u.com熱心網友回復:
根據Python 的檔案__bool__
:
呼叫實作真值檢測和內置運算
bool()
;應該回傳 False 或 True。當此方法未定義時__len__()
,如果已定義,則呼叫該方法,如果其結果為非零,則認為該物件為真。如果一個類既不定義__len__()
也不定義__bool__()
,它的所有實體都被認為是真的。
換句話說,如果__bool__
不存在,我們檢查__len__() != 0
. 如果__len__
不存在,則答案始終為True
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/485480.html