简体   繁体   English

自我陈述什么时候是真的,什么时候是假的?

[英]When is self statement true and when is false?

Can someone explain this if self.cards condition?如果 self.cards 条件,有人可以解释这一点吗? 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.首先,您应该在第一次使用 self.cards 时向我们展示。
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.假设它是某种容器( listsetdict ),如果其中有元素,则为真,如果为空,则为假。

Any object can be tested for truth value in Python.任何对象都可以在 Python 中测试真值。 The following values are considered false:以下值被认为是错误的:

None没有任何

False错误的

zero of any numeric type, for example, 0 , 0L , 0.0 , 0j .任何数字类型的零,例如00L0.00j

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 .用户定义类的实例,如果该类定义了__nonzero__()__len__()方法,则该方法返回整数零或布尔值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.在这种情况下,cards 为空时为False ,因为它是一个列表。 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.创建对象时, __init__()创建卡片空列表,因此创建对象时 if 语句的条件始终为False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM