为什么我不能在 Python 中扩展 bool? [英] Why I can't extend bool in Python?

查看:29
本文介绍了为什么我不能在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆