Can someone explain this if self.cards condition? When will it be True and when will it be False?
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + " "
else:
rep = "<empty>"
return rep
Any object can be tested for truth value in Python. The following values are considered false:
None
False
zero of any numeric type, for example, 0
, 0L
, 0.0
, 0j
.
any empty sequence, for example, ''
, ()
, []
.
any empty mapping, for example, {}
.
instances of user-defined classes, if the class defines a __nonzero__()
or __len__()
method, when that method returns the integer zero or bool value False
.
All other values are considered true — so objects of many types are always true.
In this case cards is False
when it is empty because it is a list. When the object is created, __init__()
creates the cards empty list, so that if statement's condition is always False
when the object is created.