Python創建類的時候為什麼要繼承新式類?看完這篇文章或許你就明白了。 ...
自己搬運自己在知乎上的回答,感覺破乎吃棗藥丸,哪天掛了這裡就是個備份。
鏈接:https://www.zhihu.com/question/19754936/answer/229327803
2017/9/25更新:
=============
剛剛纔知道Java里的Object類也是所有class的父類。。這麼說Python的新式類是從Java借鑒過來的?
2017/9/13原答案:
=============
自學Learn Python The Hard Way看到了這個問題,樓上各位回答講真我是看的一頭霧水。。
然後去stackoverflow搜索了一下,結合官方文檔,說一下我自己的理解:
2 PEPs 252 and 253: Type and Class Changes
First, you should know that Python 2.2 really has two kinds of classes: classic or old-style classes, and new-style classes. The old-style class model is exactly the same as the class model in earlier versions of Python. All the new features described in this section apply only to new-style classes. This divergence isn't intended to last forever; eventually old-style classes will be dropped, possibly in Python 3.0.
So how do you define a new-style class? You do it by subclassing an existing new-style class. Most of Python's built-in types, such as integers, lists, dictionaries, and even files, are new-style classes now. A new-style class named object, the base class for all built-in types, has also been added so if no built-in type is suitable, you can just subclass object:
其實這裡已經說得很清楚,Python 2.2有兩種類:舊式類、新式類。舊式類是什麼樣的暫時不用管,只要記住,以後都用並且只用新式類,就對了。
那麼怎麼來聲明或定義(define)一個新式類呢?做法就是,從現有的新式類中創建子類。
大多數的Python的內建類型(built-in type),比如整型(integers),列表(lists),字典(dictionaries),甚至文件(files),現在都是新式類了。我們也添加了一個叫object的新式類,作為所有內建類型的基類(base class),所以如果沒有適合的內建類型,從object創建子類就好了:
class C(object):
def __init__ (self):
...
...
所以現在明白了嗎?object只是從Python 2.2開始被引入的一個新式類(new-style class),作用是所有內建類型(built-in types)的基類(base class),而新式類需要從現有的新式類中創建,所以如果沒有適合的,用object就好了,就是這麼簡單。
至於新式類和舊式類的區別,網上有很多文章,可以自行查閱學習
(其實只是因為我不知道。。