2010-01-31 72 views
23
>>> 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信任程序員。爲什麼我不能在Python中擴展bool?

+10

是否要添加FileNotFound值? – Juliano 2010-01-31 15:34:12

+1

谷歌搜索或SO搜索「組合與繼承」在這裏可能很有用。 – MatrixFrog 2010-01-31 21:05:12

回答

41

圭多的對其採取:

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

+14

True和False是單例。這是一個更好的答案。 – 2010-01-31 15:36:00

+1

有用的東西是一致的:class Foo(None .__ class__):...' - >'TypeError:type'NoneType'不是可接受的基類型' – 2017-02-01 14:43:28

4

因爲bool應該只有兩個值 - TrueFalse。如果你能夠子類bool,你可以爲它定義任意數量的值,這絕對不是你想要發生的。

一個更好的問題是:爲什麼要擴展bool?

+0

我想添加一個屬性,讓我跟蹤對象上的一些內容。 – 2010-01-31 15:34:01

+4

@Juanjo然後你想要的不是一個布爾值,它是一個布爾值和其他東西的元組。布爾值必須是True或False,不能有其他值,也不能有其他屬性,這會使該類的一個實例與True和False進行負面比較。它會發生,它不會再是布爾值了。 – Juliano 2010-01-31 15:56:09

+0

好的,但我無法重寫int .__ nonzero__來返回這個元組。我可以嗎? – 2010-01-31 15:59:47

5

如果您正在使用Python 3,你想有一個可以作爲一個布爾值來評價一類,還含有其它功能,在你的班級實施__bool__

在Python 2中,通過實現__nonzero____len__(如果您的類是容器),可以實現相同的效果。

+3

在Python 2.x中,您可以通過實現'__nonzero__'或'__len__'。 – 2010-01-31 15:32:11

+0

我想要1和2來返回我的課程的一個實例。你會怎麼做? – 2010-01-31 15:37:34

+2

首先繼承bool,然後重寫int方法......爲什麼不從頭開始創建自己的類? – Agos 2010-01-31 16:33:14

9

由於OP在評論中提到:

I want 1 and 2 to return an instance of my class.

我想指出的是,這是完全不可能是很重要的:Python沒有讓你改變內置類型(和,特別是,他們的特殊方法)。文字1將永遠是一個實例內置int類型,在任何情況下and操作的基本語義不重寫反正 - a and b總是相同b if a else a任何ab(無bool脅迫即使OP似乎錯誤地認爲其中一個正在發生)。

重申發佈這一關鍵點:的a and b總是不變地要麼ab - 有沒有打破這種語義約束(即使ab是你自己獨特的類的實例方式 - - 當然,當它們被限制爲Python內置的實例int! - 時更是如此 - )。