自己搬运自己在知乎上的回答,感觉破乎吃枣药丸,哪天挂了这里就是个备份。

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

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

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

最新文章

  1. 正则表达式入门(六)匹配unicode和其他字符
  2. C# 6.0部分新特性
  3. 前端新手分析 AJAX执行顺序,数据走向
  4. 使用eclipse maven遇到的错误(转)
  5. python 类成员函数
  6. MP算法和OMP算法及其思想
  7. sed文本处理--文本行扩展与分割
  8. eclipse js中 选中方法按F3快捷键不能跳转到对应方法的解决方案
  9. 魔棒工具--RegionGrow算法简介
  10. 解读QML之三
  11. Mahout fp-growth
  12. Little Sub and Isomorphism Sequences ZOJ - 4089
  13. NetCore部署到Linux服务器+Supervisor的步骤及过程中踩过的坑
  14. 关于TCP/IOCP构架中出现的Socket假死连接解决方案
  15. CF1080
  16. ASP.net MVC模式介绍(一)
  17. C++学习(十四)(C语言部分)之 数组
  18. Centos7 安装mysql5.7.24
  19. jmeter如何保持JSESSIONID
  20. vs下C++内存泄露检测

热门文章

  1. 用VS2010构建MASM的编程环境,开始使用MASM(翻译自《Inetl汇编语言程序设计》一书的作者Kip R. Irvine的文章Getting Started with MASM),两种方法搭建IA-32汇编设计环境
  2. 如何作为一个优秀的ERP实施顾问
  3. 【MyEclipse常见错误】-java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory的解决
  4. Qt+VS编译器:默认库“library”与其他库的使用冲突;使用 /NODEFAULTLIB:library(我曾经碰到过,修改qmake.conf,但我修改的是VS的IDE配置)good
  5. reset.css(样式重置)
  6. 3017C语言_文件
  7. java基础(1)-几种获取类的扩展方式
  8. Dynamics 365 Document Management
  9. Spring Boot:实现MyBatis动态数据源
  10. JSON对象和JavaScript对象直接量的区别--不同之处