Aug-10-2021, 08:10 PM
In this code,
If
if foo:
python will call foo.__bool__()
implicitly to get the boolean value of foo
. Which is why the following code segments work,if 't': print("T") if [1]: print("T")But I wanted to check if I can call the
__bool__()
method myself like the following; 't'.__bool__() # AttributeError: 'str' object has no attribute '__bool__' [1].__bool__() # AttributeError: 'list' object has no attribute '__bool__'As you can see it do not work, and in both cases I get AttributeError.
If
__bool__()
can be called implicitly in a if statement, why can I not call it explicitly?