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?


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01