python中__init__()、__new__()、__call__()、__del__()用法
关于__new__()的用法参考:
http://www.myhack58.com/Article/68/2014/48183.htm
正文:
一、__new__()的用法:
__new__()是在新式类中新出现的方法,它作用在构造方法建造实例之前,可以这么理解,在Python 中 存在于类里面的构造方法__init__()负责将类的实例化,而在__init__()启动之前,__new__()决定是否 要使用该__init__()方法,因为__new__()可以调用其他类的构造方法或者直接返回别的对象来作为本类 的实例。

# encoding:utf-8 class A(object):
def __new__(cls, x):
print 'this is in A.__new__, and x is ', x
return super(A, cls).__new__(cls) def __init__(self, y):
print 'this is in A.__init__, and y is ', y class C(object):
def __new__(cls, n):
print 'this is in C.__new__, and n is ', n
return super(C, cls).__new__(cls) def __init__(self, a):
print 'this is in C.__init__, and a is ', a class B(A):
def __new__(cls, z):
print 'this is in B.__new__, and z is ', z
return A.__new__(cls, z) def __init__(self, m):
print 'this is in B.__init__, and m is ', m # class B(A):
# def __new__(cls, z):
# print 'this is in B.__new__, and z is ', z
# return object.__new__(cls)
# def __init__(self, m):
# print 'this is ni B.__init__, and m is ', m if __name__ == '__main__':
a = A(100)
print '=' * 20
b = B(200)
print type(b)

执行的结果为:

this is in A.__new__, and x is 100
this is in A.__init__, and y is 100
====================
this is in B.__new__, and z is 200
this is in A.__new__, and x is 200
this is in B.__init__, and m is 200
<class '__main__.B'>

说明:
1.定义A类作为下面类的父类,A类继承object类,因为需要重写A类的__new__()函数,所以需要继承object基类,成为新式类,经典类没有__new__()函数;
2.子类在重写__new__()函数时,写return时必须返回有继承关系的类的__new__()函数调用,即上面代码中的B类继承自A类,则重写B类的__new__()函数,写return时,只能返回A.__new__(cls)或者object.__new__(cls),不能返回C类的;
3.由注释掉的代码执行结果可以看出,B类虽然继承自A类,但是如果没有重写B类的__new__()函数,则默认继承的仍是object基类的__new__(),而不是A的;
4.B类的__new__()函数会在B类实例化时被调用,自动执行其中的代码语句,但是重写__new__()函数不会影响类的实例化结果,也就是说不管写return时返回的是A的还是object的,B类的实例化对象就是B类的,而不会成为A类的实例化对象;只是在实例化时,如果返回的是A.__new__(cls),则会执行A类中定义的__new__()函数;
5.__new__()函数确定了类的参数的个数,object类默认定义的__new__()函数的参数为(cls, *more),但如果在子类中重写了__new__(cls, x), 则实例化类时,需要传入一个x参数,而__init__()函数接受到的有两个参数,一个是实例化生成的实例对象self代替,一个是传入的实参x的值;

>>>
>>> class A(object):
def __init__(self, x):
self.x = x
print '__init__ called.'
def foo(self):
print self.x >>>
>>> a = A('123')
__init__ called.
>>>
>>> a.foo()
123
>>>

在A('123')实例化类时,自动调用__init__()方法定义的self.x = x和print '__init__ called.',我们能看到‘__init__ called.’被打印,看不到self.x = x的执行,但是在调用a.foo()时,能执行成功,就是拜self.x = x的功能所赐;因为如果没有__init__()方法中的self.x = x,实例对象将无法追溯到foo()函数中的self.x是从哪里来的,从而会报错;也就是在__init__()函数中将外部传入的参数x赋值给self.x,从而是self.x在类A中畅行无阻;
三.__call__()的用法
__call__()方法能够让类的实例对象,像函数一样被调用;

>>>
>>> class A(object):
def __call__(self, x):
print '__call__ called, print x: ', x >>>
>>> a = A()
>>> a('123')
__call__ called, print x: 123
>>>

看a('123')这是函数的调用方法,这里a实际上是类对象A的实例对象,实例对象能想函数一样传参并被调用,就是__call__()方法的功能;
四、__del__()的用法
如果__new__()和__init__()函数时类的构造函数(即在类实例化时自动执行函数中定义的内容),那么__del__()是类的析构函数,是python垃圾回收机制的实际应用,当类的所有引用都被删除后,该类就会被系统从内存中删除,注意是所有的引用都被删除哦,而不是每一次删除;

>>> class D(object):
def __init__(self):
print 'this is D.__init__()'
def __del__(self):
print 'this is D.__del__()' >>>
>>> d = D()
this is D.__init__()
>>>
>>> d2 = d
>>> d3 = d
>>>
>>> del d
>>> del d2
>>> del d3
this is D.__del__()
>>>

将D()实例化对象赋值给d,后d2,d3都是指向D()的这次实例化对象,删除d和d2的引用都不会触发__del__()函数,最后一个d3的引用被删除,就会触发__del__(),此时D()的这一次实例化的对象就被清除;
最后:
用一段简单的代码,来总体感受一下三个方法的用法和区别:

>>>
>>> class A(object):
def __init__(self, x):
print 'x in __init__', x
def __new__(cls, y):
print 'y in __new__', y
return super(A, cls).__new__(cls)
def __call__(self, z):
print 'z in __call__', z
def __del__(self):
print 'this is in A.__del__()' >>>
>>> A('123')('abc')
y in __new__ 123
x in __init__ 123
z in __call__ abc
this is in A.__del__()
>>>

由执行结果可以看出,虽然__init__()方法定义在__new__()方法之前,但是结果中先展示了__new__()方法的执行结果;
python中__init__()、__new__()、__call__()、__del__()用法的更多相关文章
- Python中的__new__和__init__
Python中的__new__和__init__ 写了这么多的class,现在才知道还有个__new__方法, 那么它和__init__有什么区别呢? class TestCls(): "& ...
- Python中的__new__()方法与实例化
@Python中的__new__()方法与实例化 __new__()是在新式类中新出现的方法,它作用在构造方法建造实例之前,可以这么理解,在Python 中 存在于类里面的构造方法__init__ ...
- Python中【__all__】的用法
Python中[__all__]的用法 转:http://python-china.org/t/725 用 __all__ 暴露接口 Python 可以在模块级别暴露接口: __all__ = [&q ...
- 简单说明Python中的装饰器的用法
简单说明Python中的装饰器的用法 这篇文章主要简单说明了Python中的装饰器的用法,装饰器在Python的进阶学习中非常重要,示例代码基于Python2.x,需要的朋友可以参考下 装饰器对与 ...
- python中__init__.py文件的作用
问题 在执行models.py时,报ImportError:No module named transwarp.db的错误,但明明transwarp下就有db.py文件,路径也没有错误.真是想不通.后 ...
- Python中__init__方法介绍
本文介绍Python中__init__方法的意义. __init__方法在类的一个对象被建立时,马上运行.这个方法可以用来对你的对象做一些你希望的 初始化 .注意,这个名称的开始和结尾 ...
- Python中__init__.py文件的作用详解
转自http://www.jb51.net/article/92863.htm Python中__init__.py文件的作用详解 http://www.jb51.net/article/86580. ...
- python中enumerate()函数用法
python中enumerate()函数用法 先出一个题目:1.有一 list= [1, 2, 3, 4, 5, 6] 请打印输出:0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 打印输 ...
- Python中try...except...else的用法
Python中try...except...else的用法: try: <语句>except <name>: <语句> #如果在try ...
- Python中logging模块的基本用法
在 PyCon 2018 上,Mario Corchero 介绍了在开发过程中如何更方便轻松地记录日志的流程. 整个演讲的内容包括: 为什么日志记录非常重要 日志记录的流程是怎样的 怎样来进行日志记录 ...
随机推荐
- POJ 2096 Collecting Bugs 期望dp
题目链接: http://poj.org/problem?id=2096 Collecting Bugs Time Limit: 10000MSMemory Limit: 64000K 问题描述 Iv ...
- 【CS231N】3、Softmax分类器
wiki百科:softmax函数的本质就是将一个K维的任意实数向量压缩(映射)成另一个K维的实数向量,其中向量中的每个元素取值都介于(0,1)之间. 一.疑问 二.知识点 1. softmax函数公式 ...
- Internet History, Technology and Security (Week4)
Week4. We are now moving into Week 4! This week, we will be covering commercialization and growth. T ...
- ns3 回调机制
(1)目的:为了实现两个模块之间的通信(这两个模块没有任何依赖关系) (2) C语言中的函数指针 int (*a)(int q) = 0; //声明一个函数指针a,初始值设为0 //. //. //. ...
- 转载---Atom编辑器常用快捷键
常用快捷键–亲测及翻译 英文 中文 快捷键 功能 New Window 新建界面窗口 Ctrl + Shift + N 如中文意思 New File 新建文件 Ctrl + N 如中文意思 Open ...
- ISCC2018(misc)
ISCC2018 misc writeup(部分) 这些天做个了iscc题目,有些题目不是很难,网上都有相同的题或者类似的题目,但是我很菜,没做出来多少. #misc1:Where is the FL ...
- (三)使用Jmeter模拟300个用户登录
1.首先在系统中创建300个用户(在这里使用 pl/sql 进行循环创建): 代码如下: --先对原先的表进行备份 :CREATE TABLE sys_user_bak AS SELECT * FRO ...
- C语言以字符形式读写文件
一.字符读取函数 fgetc (一).函数介绍 fgetc 是 file get char 的缩写,意思是从指定的文件中读取一个字符.函数原型为: int fgetc(FILE* fp) fp 为文件 ...
- 有意思的Alias参数
1. 最简单的方式,运行正常. PS C:\> Get-Service -Name BITS -ComputerName localhost 2. 自己构造一个对象,试图通过管道将主机名传递下去 ...
- Jquery 表单提交后3s禁用
<form action="${pageContext.servletContext.contextPath}/XXX/###" method="post" ...