将None与Python3中的几个变量进行比较

时间:2019-11-24 22:17:22

标签: python types nonetype

有没有人能告诉我为什么我得到这种类型的返回值?

>>> a = 7
>>> b = None
>>> bool(a and b)
False
>>> bool((a is None) and (b is None))
False
>>> bool((a and b) is None) # (a and b) eq False
True
>>> bool(False is None)
False

我只是不明白为什么会这样。

4 个答案:

答案 0 :(得分:2)

解释

>>> 7 and None
None
>>> bool(None)
False

要回答:

    注释时,
  • a and b给出None False
  • bool(a and b)给出False

因此,当您将a and b替换为实际值时:

  • 您得到bool(None is None),即True

我相信您会想到bool(bool(a and b) is None),这会给False

答案 1 :(得分:0)

Python的and实际上返回测试的最后一个值。对于x and y,如果x为假,它将返回x;如果x为true,它将返回y。例如:

>>> 0 and ''
0
>>> 0 and 'x'
0
>>> 1 and ''
''
>>> 1 and 'x'
'x'

因此,当您执行a and b时,您会得到None

来源:Documentation: Boolean Operations — and, or, not

答案 2 :(得分:0)

考虑以下两个事实:

  1. Map是错误的
  2. None如果两个变量都为true,则返回true。

在每种情况下都会误导您,您没有考虑这些事实。

答案 3 :(得分:0)

所有Python内置程序和大多数实例由于其__bool__ magic methods而具有隐式的真值。在您的情况下,您正在使用ILocationListener public class FusedLocationProviderCallback : LocationCallback { readonly MainActivity activity; public FusedLocationProviderCallback(MainActivity activity) { this.activity = activity; } public override void OnLocationAvailability(LocationAvailability locationAvailability) { Log.Debug("FusedLocationProviderSample", "IsLocationAvailable: {0}",locationAvailability.IsLocationAvailable); } public override void OnLocationResult(LocationResult result) { if (result.Locations.Any()) { var location = result.Locations.FirstOrDefault(); //Do something } else { //Do something else if no location received. } } } 的内置类型。在纯python中,用于int的{​​{1}}方法将类似于以下内容:

None

对于__bool__,它将是以下内容:

int

每当需要将变量视为布尔值的操作(class int(object): ... def __bool__(self): return self != 0 # True as long as not equal to 0 ... Noneclass NoneType(object): ... def __bool__(self): return False # Always False ... and强制转换)时,这些{{1} }魔术方法用于获取其相应实例的真实值。

因此,请记住这一点。

or

not是整数bool,因此通过其__bool__魔术方法,它具有正真值(>>> bool(a and b) False )。 a7,并且它具有负真值(__bool__)。当您在Python中使用True变量时,如果第一个b操作数具有正真值,则None将始终返回第二个操作数(False可以看到相反的行为)。有关更多信息,请参见here。因此,当您执行and时,将返回and,因为and具有正的真值。然后将得到的or强制转换为a and b,如上面None的{​​{1}}方法所示,将为a

None

由于bool不是None,因此计算结果为False。在这里,由于您在语句中使用__bool__,因此您没有在比较真值,而是在检查它们是否是同一对象。由于False>>> bool((a is None) and (b is None)) False 不是同一实例,因此结果为a,导致语句的其余部分求值为None

is

从第一个开始,7将返回None。由于FalseFalse是同一实例,因此>>> bool((a and b) is None) # (a and b) eq False (should be None) True 的值为a and b。强制转换为None

None

最后,我们在这里再次检查NoneNone is None是否是同一实例。由于不是,因此计算结果为True,而对bool的强制转换又是多余的。