Weekly backup.
This commit is contained in:
56
20220528161514-la_methode_bool.org
Normal file
56
20220528161514-la_methode_bool.org
Normal file
@@ -0,0 +1,56 @@
|
||||
:PROPERTIES:
|
||||
:ID: 5803422c-c089-4369-93cc-80caca71a26b
|
||||
:mtime: 20220528173751
|
||||
:ctime: 20220528161514
|
||||
:END:
|
||||
#+title: La méthode __bool__
|
||||
|
||||
* Synthaxe
|
||||
#+BEGIN_SRC python
|
||||
object.__bool__(self)
|
||||
#+END_SRC
|
||||
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
|
||||
#+BEGIN_SRC python :results output
|
||||
print(f'{bool(None) = }')
|
||||
|
||||
print(f'{bool([]) = }')
|
||||
print(f'{bool([None]) = }')
|
||||
|
||||
print(f'{bool({}) = }')
|
||||
|
||||
#+END_SRC
|
||||
#+RESULTS:
|
||||
: bool(None) = False
|
||||
: bool([]) = False
|
||||
: bool([None]) = True
|
||||
: bool({}) = False
|
||||
|
||||
* Par défaut, les instances de classes retournent /True/ :
|
||||
#+BEGIN_SRC python :results output
|
||||
class Dummy:
|
||||
pass
|
||||
|
||||
print(f'{bool(Dummy()) = }')
|
||||
#+END_SRC
|
||||
#+RESULTS:
|
||||
: bool(Dummy()) = True
|
||||
|
||||
#+BEGIN_SRC python :results output
|
||||
class Dummy:
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return False
|
||||
|
||||
print(f'{bool(Dummy()) = }')
|
||||
#+END_SRC
|
||||
#+RESULTS:
|
||||
: bool(Dummy()) = False
|
||||
|
||||
* Références
|
||||
* [[https://mathspp.com/blog/pydonts/truthy-falsy-and-bool][Truthy falsy and bool - Pydon't]]
|
||||
|
Reference in New Issue
Block a user