2015-11-08 34 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

簡而言之,您不能將屬性添加到基元,但您可以對它們進行子類化(除非無法)。

相關問題