CKTIS / Python
Palabra clave if
Prueba la veracidad según Python sin comparar la condición con True.
Versión: Python 3.14; repository image, production runtime not attested
Sintaxis
if condition:
...
else:
...Prueba la veracidad según Python sin comparar la condición con True.
Un objeto puede definir __bool__ o, en su ausencia, __len__. Solo se ejecuta el bloque elegido. and y or pueden omitir operandos por cortocircuito.
Si existen ambos, un __bool__ verdadero prevalece incluso con __len__ cero.
Ejemplos
class Stock:
def __init__(self, units):
self.units = units
def __len__(self):
return self.units
for item in (Stock(0), Stock(2)):
if item:
print("ready")
else:
print("empty")
class Priority(Stock):
def __bool__(self):
return True
if Priority(0):
print("bool wins")
Resultado
empty ready bool wins
Si existen ambos, un `__bool__` verdadero prevalece incluso con `__len__` cero.