为什么我不能在Python扩展布尔? [英] Why I can't extend bool in Python?
问题描述
>>> 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程序员。
推荐答案
圭多我们来就可以了:
我想过这个最后
晚上,意识到你不应该
被允许在所有子类布尔!一个
子类只会是有用的,当它
有实例,但单纯的所有脑干
布尔的子类的实例
将打破不变,真正的
和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.
参考:<一href=\"http://mail.python.org/pipermail/python-dev/2002-March/020822.html\">http://mail.python.org/pipermail/python-dev/2002-March/020822.html
这篇关于为什么我不能在Python扩展布尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!