1:__new__:它是创建对象时调用,会返回当前对象的一个实例;

__init__:它是创建对象后调用,对当前对象的一些实例初始化,无返回值

代码示例:

>>> class Data(object):
def __init__(cls):
cls.x = 2
print "init"
return cls ###在init中不可用 >>> data = Data()
init Traceback (most recent call last):
File "<pyshell#100>", line 1, in <module>
data = Data()
TypeError: __init__() should return None, not 'Data' >>> class Data(object):
def __new__(cls):
cls.x = 3
print "new"
return cls >>> data = Data()
new
>>> data.x
3

由上可见,__new__方法会返回所构造的对象,__init__则不会,__init__无返回值

2:再类中,若__new__和__init__同时存在时,先调用__new__

代码示例:

>>> class Data(object):
def __new__(self):
print "new"
def __init__(self):
print "init" >>> data = Data()
new

3:If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

如果__new__返回一个对象的实例,会隐式调用__init__

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

如果__new__不返回一个对象的实例,__init__不会被调用

代码示例:

>>> class A(object):
def __new__(Class):
object = super(A,Class).__new__(Class)
print "in new"
return object ##返回对象的实例
def __init__(self):
print "in init" >>> A()
in new
in init
<__main__.A object at 0x0215CD70>
>>> class B(object):
def __new__(cls):
print "in new"
return cls
def __init__(self):
print "in init" >>> b=B()
in new

最新文章

  1. 【bzoj4423】 AMPPZ2013—Bytehattan
  2. linux查看负载
  3. js 事件处理程序 事件对象
  4. 我的Github之旅(一)
  5. [译]Exploring Angular 1.3: Binding to Directive Controllers
  6. oracle sql 优化
  7. 记录nginx 搭建集群环境踏过的坑
  8. JAVA如何将PDF转换SWF格式的FLASH
  9. #define用法集锦[修正版]
  10. Tabbar视图切换,返回上一视图,添加item
  11. ASPNET中实现在线用户检测(使用后台守护线程)
  12. iis7 发布mvc3 遇到的HTTP错误 403.14-Forbidden Web 服务器被配置为不列出此目录的内容及Login on failed for &quot;IIS APPPOOL\ASP.NET v4.0&quot;问题
  13. shell script 零碎知识
  14. Recover Polygon (easy)
  15. Github 开源:使用升讯威 Mapper( Sheng.Mapper)与 AutoMapper 互补,大幅提高开发效率!
  16. MySQL安装与启动——Windows系统下
  17. 【ES】学习10-聚合3
  18. 读书笔记——《redis入门指南(第2版)》第三章 入门
  19. txt,csv,json互相转化
  20. flannel

热门文章

  1. 苦逼IT才能看懂的笑话
  2. css hack(部分)
  3. Allegro PCB中封装焊盘替换操作详解
  4. Dos下mySql
  5. 【LeetCode with Python】 Sort List
  6. BUAAOO P13-P14 UML Interaction
  7. ffmpeg强制使用TCP方式推流到EasyDarwin开源流媒体服务器进行直播
  8. 使用Primose方式解决异步编程回调的一些问题--animate动画的例子
  9. php递归循环地区
  10. RobotFramework教程使用笔记——RIDE的相关知识及Resources创建关键字文件