1.2 KiB
1.2 KiB
La méthode bool
Synthaxe
object.__bool__(self)
La méthode object.__bool__
:
- “Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below [or, and and not].”,
- Un objet est Falsy lorsqu'il est empty ou without any useful value,
- Est appelée par la fonction built-in bool.
Exemples
print(f'{bool(None) = }')
print(f'{bool([]) = }')
print(f'{bool([None]) = }')
print(f'{bool({}) = }')
bool(None) = False bool([]) = False bool([None]) = True bool({}) = False
- Par défaut, les instances de classes retournent True :
class Dummy:
pass
print(f'{bool(Dummy()) = }')
bool(Dummy()) = True
class Dummy:
def __bool__(self) -> bool:
return False
print(f'{bool(Dummy()) = }')
bool(Dummy()) = False