当我们要判断一个值的真假时,往往使用bool(object)方法, 它会判断对象(object)的真假,并返回True或False。但是一直没明白为什么可以直接用bool()或者len()方法。
原来bool(object), 其实背后是调用的object.bool方法的结果,如果该对象不存在bool方法,则python会调用len方法。如果返回0则bool()返回False,否则返回True。默认情况下我们自定义的类的实例会被认为是真的,除非自定义的类的bool和len方法有其他实现
首先看下面 x 有哪些方法:
In [1]: x = 0
In [2]: dir(x)
Out[2]:['__abs__','__add__','__and__','__bool__','__ceil__','__class__','__delattr__','__dir__','__divmod__','__doc__','__eq__','__float__','__floor__','__floordiv__','__format__','__ge__','__getattribute__','__getnewargs__','__gt__','__hash__','__index__','__init__','__int__','__invert__','__le__','__lshift__','__lt__','__mod__','__mul__','__ne__','__neg__','__new__','__or__','__pos__','__pow__','__radd__','__rand__','__rdivmod__','__reduce__','__reduce_ex__','__repr__','__rfloordiv__','__rlshift__','__rmod__','__rmul__','__ror__','__round__','__rpow__','__rrshift__','__rshift__','__rsub__','__rtruediv__','__rxor__','__setattr__','__sizeof__','__str__','__sub__','__subclasshook__','__truediv__','__trunc__','__xor__','bit_length','conjugate','denominator','from_bytes','imag','numerator','real','to_bytes']
In [3]: bool(x)
Out[3]: False
这里看到我们在创建x变量时,因为x此时是int类的实例,int类有bool方法。所以如果此时调用bool(x),则实际使用的是x的bool内建方法。
而如果x是字符串str呢?
In [5]: dir(x)
Out[5]:
['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','capitalize','casefold','center','count','encode','endswith','expandtabs','find','format','format_map','index','isalnum','isalpha','isdecimal','isdigit','isidentifier','islower','isnumeric','isprintable','isspace','istitle','isupper','join','ljust','lower','lstrip','maketrans','partition','replace','rfind','rindex','rjust','rpartition','rsplit','rstrip','split','splitlines','startswith','strip','swapcase','title','translate','upper','zfill']
In [6]: bool(x)
Out[6]: True
此时x是str类的实例,str类没有bool内建方法,则python会调用len方法,如果返回0则bool()返回False, 否则返回True。
上面因为x的长度不为0 则返沪Ture,接下来看一下空字符串:
In [7]: x = ""
In [8]: bool(x)
Out[8]: False
可以看到由于a的长度为0 ,所以bool()返回False
接下来定义一个类试试
In [9]: class Test():
...: pass
In [10]: t = Test()
In [11]: bool(t)
Out[11]: True
得到的结果为True,因为我们没有自定义bool或len。默认情况下自定义的类的实例总是被认为是真的True。
我们自定义一下Test的bool方法:
In [12]: class Test():
...: def __bool__(self):
...: return False
In [13]: t = Test()
In [14]: bool(t)
Out[14]: False
其实非常好理解!!!