python的class attribute

前兩天被這個東西給陰到了,只怪我沒搞清楚,這在 Learning python 2nd 裡的 21.1 裡寫的很清楚。不過我想,從Java/C++/C#跳槽過來的人應該都會搞糊塗吧~

以C++舉例,下面的code:
[cpp]class Object {
private:
int id;
};
[/cpp]

到了 python,應該都會很自然的寫成:
[python]# 例A
class Object:
id=0
[/python]

看起來沒錯,對吧~
不過,事實上,應該要寫成這樣才對:
[python]# 例 B
class Object:
def init(self):
self.id=0
[/python]

換句話說,例A翻譯成C++的話,其實是類似 static 的用法,也就是說,id 會變成一個共用的 static 變數:
[cpp]class Object {
private:
static int id;
};
[/cpp]