Why I can#39;t extend bool in Python?(为什么我不能在 Python 中扩展 bool?)
问题描述
>>> class BOOL(bool):
... print "why?"
...
why?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
我认为 Python 信任程序员.
推荐答案
Guido 的看法:
我最后想到了这个晚上,并意识到你不应该完全可以继承 bool !一个子类只有在它有用时才有用有实例,但仅仅是存在bool 子类的实例会打破 True 的不变量和 False 是唯一的实例布尔!(C 的子类的一个实例也是 C 的一个实例.)我认为重要的是不要提供后门创建额外的布尔实例,所以我认为 bool 不应该可以子类化.
I thought about this last night, and realized that you shouldn't be allowed to subclass bool at all! A subclass would only be useful when it has instances, but the mere existance of an instance of a subclass of bool would break the invariant that True and False are the only instances of bool! (An instance of a subclass of C is also an instance of C.) I think it's important not to provide a backdoor to create additional bool instances, so I think bool should not be subclassable.
参考:http://mail.python.org/pipermail/python-dev/2002-March/020822.html
这篇关于为什么我不能在 Python 中扩展 bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能在 Python 中扩展 bool?


基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01