Skip to content Skip to sidebar Skip to footer

When Is Self Statement True And When Is False?

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:

Solution 1:

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.


Solution 2:

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.


Post a Comment for "When Is Self Statement True And When Is False?"