Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么bool是int的一个子类?_Python_Boolean - Fatal编程技术网

Python 为什么bool是int的一个子类?

Python 为什么bool是int的一个子类?,python,boolean,Python,Boolean,当通过python memcached在memcached中存储bool时,我注意到它是作为整数返回的。通过检查库的代码,我发现有一个地方,isinstance(val,int)被选中以将值标记为整数 因此,我在python shell中对其进行了测试,并注意到以下几点: >>> isinstance(True, int) True >>> issubclass(bool, int) True 但是为什么bool是int的子类呢 这有点道理,因为布尔值基本上

当通过python memcached在memcached中存储bool时,我注意到它是作为整数返回的。通过检查库的代码,我发现有一个地方,
isinstance(val,int)
被选中以将值标记为整数

因此,我在python shell中对其进行了测试,并注意到以下几点:

>>> isinstance(True, int)
True
>>> issubclass(bool, int)
True
但是为什么
bool
int
的子类呢

这有点道理,因为布尔值基本上是一个int,它只能取两个值,但它需要的运算/空间比实际整数少得多(没有算术运算,只有一位存储空间)…

<

这是完全合乎逻辑的,如果你在布尔类型 添加到python中(大约2.2或2.3)

在引入实际的布尔类型之前,0和1是 真实值的官方表示,类似于C89。避 不必要地破坏了非理想但有效的代码,新的bool类型 需要像0和1一样工作。这不仅仅是真理的价值, 但是所有的积分运算。没有人会建议使用布尔值 结果是数字上下文,大多数人也不建议进行测试 平等决定真理的价值,没有人想找出难的 那么现有的代码有多少是这样的呢。因此,决定 True和False分别伪装为1和0。这只不过是一个例子 语言演变的历史产物

dman13的解释很好。

请参阅。相关通道:

6) bool应该从int继承吗

=>是的

在理想情况下,bool作为一个 知道如何执行混合模式的独立整数类型 算术。但是,从int继承bool会简化 极大地实现(部分是因为所有调用 PyInt_Check()将继续工作——对于 int的子类)


也可以使用
help
检查控制台中的
Bool
值:

帮助(正确)

帮助(错误)


这里是。值得注意的是,在Python中,一切都是一个对象,使用的开销非常大,因此通过减小
bool
s来节省空间几乎是毫无意义的。如果您关心内存的使用,那么您首先应该使用另一种语言。请注意,这在历史上可能是正确的,但习惯上您会看到很多
sum([f(value)表示value in values])
其中
f(x)
是一种过滤函数,你需要知道有多少个值通过了过滤。就我个人而言,我宁愿写
求和(如果f(value),则值中的值为1)
,但我实际上看到一些受人尊敬的人主张对布尔值进行数值运算。
help(True)
Help on bool object:
class bool(int)
 |  bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.
 |  
 |  Method resolution order:
 |      bool
 |      int
 |      object
 |  
help(False)
Help on bool object:
class bool(int)
 |  bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.
 |  
 |  Method resolution order:
 |      bool
 |      int
 |      object