2015-11-08 54 views
2

(这是不是一个原子测试和设置)是否可以向bool类添加测试和设置,测试和清除?

所有我想要的是能够写出这样的代码:的

need_cleanup = True 
... 
if need_cleanup.test_and_clear(): 
    cleanup() 

代替:

if need_cleanup: 
    cleanup() 
    need_cleanup = False 

恕我直言,这样做不要在布尔课中破坏任何东西。

试图加入一个方法结束了:

TypeError: can't set attributes of built-in/extension type 'bool'

这可能与该布尔类不能被继承的已知的限制,但我不希望它的子类。

有没有办法解决它?


编辑:我想我已经得到了答案。这是不可能的,因为布尔是不可变的。从False切换到True(反之亦然)用分别与TrueFalse常数相同的新对象代替布尔对象。显然,调用一个方法不能做到这一点。禁止的子类只是吸引我的注意...

回答

0

你不能。

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. - Guido van Rossum

简而言之,您不能将属性添加到基元,但您可以对它们进行子类化(除非无法)。