Python 为什么要继承 object 类?
自己搬运自己在知乎上的回答,感觉破乎吃枣药丸,哪天挂了这里就是个备份。
链接: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就好了,就是这么简单。
至于新式类和旧式类的区别,网上有很多文章,可以自行查阅学习
(其实只是因为我不知道。。