在python中,做这样的构造是有效的。
def a():
return 0
if a:
print "Function object was considered True"
else:
print "Function object was considered False"
我想问的是函数指针被赋值为True的逻辑是什么?
为什么要在语言中插入这种构造?
很多事情都是以 True
在Python中。从 布尔运算符的文档:
在布尔运算的情况下,以及当表达式被控制流语句使用时,以下值被解释为false。
False
,None
所有类型的数字零,以及空字符串和容器(包括字符串、元组、列表、字典、集合和frozensets)。所有其他值都被解释为真。
在Python中的函数,就像很多东西一样,都是 对象因此,在布尔语境中,它们的值为 True。因此,在布尔语境中,它们的值是 True。
在python中为False的对象列表。
None
[]
{}
empty set
empty frozenset
False
0
0.0
0L
0j
defaultdict
Classes
已实施的 __nonzero__()
方法,并返回一个虚假的值,否则的话 __len__()
被调用。在python 3x中 __bool__()
取代 __nonzero__()
.在 @Magnus Hoff 链接到的 Truth Value Testing 中,我发现最具有指导意义的语句是:"在默认情况下,对象被认为是真,除非它的类定义了一个 __bool__() 方法返回 False 或 __len__() 方法返回零,当与对象一起调用时。
默认情况下,一个对象被认为是真,除非它的类定义了一个返回False的__bool__()方法或一个返回0的__len__()方法,当调用该对象时。
我试着定义了自己的类,似乎__bool__()优先于__len__(),这是有道理的。
class Falsish(object):
def __init__(self):
self.val = "False, even though len(self) > 0"
def __bool__(self):
return False
def __len__(self):
return 2
class StillFalsish(object):
def __init__(self):
self.val = "False, even though len(self) > 0"
def __len__(self):
return 2
def __bool__(self):
return False
class Truish(object):
def __init__(self):
self.val = "True, even though len(self) = 0"
def __bool__(self):
return True
def __len__(self):
return 0
class StillTruish(object):
def __init__(self):
self.val = "True, even though len(self) = 0"
def __len__(self):
return 0
def __bool__(self):
return True
class NowFalsish(object):
def __init__(self):
self.val = "False, with no __bool__(), since len(self) = 0"
def __len__(self):
return 0
class NowTruish(object):
def __init__(self):
self.val = "True, with no __bool__(), since len(self) > 0"
def __len__(self):
return 2
mybool1 = Falsish()
mybool2 = StillFalsish()
mybool3 = Truish()
mybool4 = StillTruish()
mybool5 = NowFalsish()
mybool6 = NowTruish()
if mybool1: print("mybool1 is true")
if mybool2: print("mybool2 is true")
if mybool3: print("mybool3 is true")
if mybool4: print("mybool4 is true")
if mybool5: print("mybool5 is true")
if mybool6: print("mybool6 is true")
上述代码的输出是:
mybool2 is true
mybool3 is true
mybool6 is true