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
First, you should probably show us when self.cards is used for the first time.
Assuming it is some sort of a container( list
, set
or dict
) it will be true if there are elements in it and false if it is empty.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.