python 类继承object_Python 为什么要继承 object 类?

本文介绍了Python2.2引入的新式类概念,新式类是Python类体系的重要变革,它从旧式类中进化而来。新式类需要通过继承现有新式类来定义,如object类就是所有内置类型的基类。新式类提供了更多特性,如更好的集成性和元类支持。理解新式类对于深入Python编程至关重要。
摘要由CSDN通过智能技术生成

2017/9/25更新:

=============

刚刚才知道Java里的Object类也是所有class的父类。。这么说Python的新式类是从Java借鉴过来的?

2017/9/13原答案:

=============

自学Learn Python The Hard Way看到了这个问题,楼上各位回答讲真我是看的一头雾水。。

然后去stackoverflow搜索了一下,结合官方文档,说一下我自己的理解:

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就好了,就是这么简单。

至于新式类和旧式类的区别,网上有很多文章,可以自行查阅学习

(其实只是因为我不知道。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值