Python中的__new__和__init__

写了这么多的class,现在才知道还有个__new__方法, 那么它和__init__有什么区别呢?

class TestCls():
"""docstring for TestCls""" def __init__(self, name):
print('init')
print(self)
print(type(self))
self.name = name def __new__(cls, name):
print('new')
print(cls)
print(type(cls))
return super().__new__(cls) c = TestCls("CooMark") # new...
# <class '__main__.TestCls'>
# <class 'type'> # init...
# <__main__.TestCls object at 0x02201130>
# <class '__main__.TestCls'>

异同点


1. 参数
* \_\_new\_\_的第一个占位参数是class对象
* \_\_init\_\_的第一个占位参数是class的实例对象
* 其他的参数应一致
2. 作用
* \_\_new\_\_ 用来创建实例,在返回的实例上执行\_\_init\_\_,如果不返回实例那么\_\_init\_\_将不会执行
* \_\_init\_\_ 用来初始化实例,设置属性什么的

利用__new__我们能做哪些牛逼的事情?


>Python文档
>>object.__new__(cls[, ...])
>>Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).
>>
>>Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.
>>
>>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__().
>>
>>If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.
>>
>>__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
>>

依照Python官方文档的说法,__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。还有就是实现自定义的metaclass

假如我们需要一个永远都是正数的整数类型,通过集成int,我们可能会写出这样的代码

class PositiveInteger(int):

    def __init__(self, value):
super().__init__(self, abs(value)) i = PositiveInteger(-3)
print(i)
# # TypeError: object.__init__() takes no parameters class PositiveInteger(int): def __new__(cls, value):
return super(PositiveInteger, cls).__new__(cls, abs(value))
i = PositiveInteger(-3)
print(i)
# 3
  • 用__new__来实现单例
class Singleton(object):
def __new__(cls):
# 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
obj1 = Singleton()
obj2 = Singleton()
obj1.attr1 = 'value1'
print( obj1.attr1, obj2.attr1)
print( obj1 is obj2)
 

Python中的__new__和__init__的更多相关文章

  1. 一个案例深入Python中的__new__和__init__

    准备 在Python中,一切皆对象. 既然一切皆对象,那么类也是对象,我们暂且称之为 类对象.来个简单例子(本篇文章的所有案例都是运行在Python3.4中): class foo(): pass p ...

  2. python中的__new__与__init__,新式类和经典类(2.x)

    在python2.x中,从object继承得来的类称为新式类(如class A(object))不从object继承得来的类称为经典类(如class A()) 新式类跟经典类的差别主要是以下几点: 1 ...

  3. python 中的__new__与__init__

    在Python中的class中有两个方法__new__与__init__,有什么区别呢? class TestCls(): """docstring for TestCl ...

  4. python中的__new__、__init__和__del__

    __new__.__init__.__del__三个方法用于实例的创建和销毁,在使用python的类中,我们最常用的是__init__方法,通常称为构造方法,__new__方法几乎不会使用,这篇文章是 ...

  5. Python 中的__new__和__init__的区别

    [同] 二者均是Python面向对象语言中的函数,__new__比较少用,__init__则用的比较多. [异] __new__是在实例创建之前被调用的,因为它的任务就是创建实例然后返回该实例对象,是 ...

  6. 详解Python中的__new__、__init__、__call__三个特殊方法(zz)

    __new__: 对象的创建,是一个静态方法,第一个参数是cls.(想想也是,不可能是self,对象还没创建,哪来的self)__init__ : 对象的初始化, 是一个实例方法,第一个参数是self ...

  7. Python中的__new__()方法与实例化

    @Python中的__new__()方法与实例化   __new__()是在新式类中新出现的方法,它作用在构造方法建造实例之前,可以这么理解,在Python 中 存在于类里面的构造方法__init__ ...

  8. Python中:self和__init__的含义 + 为何要有self和__init__

    Python中:self和__init__的含义 + 为何要有self和__init__ 背景 回复: 我写的一些Python教程,需要的可以看看 中SongShouJiong的提问: Python中 ...

  9. 转载--------Python中:self和__init__的含义 + 为何要有self和__init__

    背景 回复:我写的一些Python教程,需要的可以看看,中SongShouJiong的提问: Python中的self,__init__的含义是啥?为何要有self,__init这些东西? 解释之前, ...

随机推荐

  1. 【动态规划】bzoj1663 [Usaco2006 Open]赶集

    http://blog.csdn.net/u011265346/article/details/44906469 #include<cstdio> #include<algorith ...

  2. HDU 4405 Aeroplane chess (概率DP)

    题意:你从0开始,要跳到 n 这个位置,如果当前位置是一个飞行点,那么可以跳过去,要不然就只能掷骰子,问你要掷的次数数学期望,到达或者超过n. 析:概率DP,dp[i] 表示从 i  这个位置到达 n ...

  3. C#匿名函数的坑

    在for循环中catch索引 for (int i = 0; i < n; i++) { foo(() =>{ if (i == x) //这里的i始终都是最后一个... { //bala ...

  4. swift的运算符

    1.什么是运算符?它有什么作用? 运算符是一种特定的符号或者表达式.它用来验证.修改.合并变量. 2.运算符有哪些? 运算符有很多,很多朋友学的很烦.这里我依据它的作用把它分为几块来介绍: a:赋值运 ...

  5. 甲乙(数理逻辑)转自http://www.cnblogs.com/devymex/p/3329635.html

    这是一道历史悠久,又很困难的面试题. 你在旁观主持人和甲.乙两个天才数学家玩猜数字游戏.主持人准备了两个数,告知甲乙:这两个数不同,且大于等于1,小于等于30.然后主持人将两数之积告诉甲,把两数之和告 ...

  6. (转)Windows下的Memcached安装与使用

    WHAT Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memc ...

  7. javascript replace正则替换时调用函数替换的使用

    以下函数将替换英文方式下的单引号和双引号,当然change函数编写决定了你要替换什么? String.prototype.repSpecChar=function()      {           ...

  8. 不写1行代码,在Mac上体验ASP.NET 5的最简单方法

    昨天微软发布了ASP.NET 5 beta2(详见ASP.NET 5 Beta2 发布),对ASP.NET 5的好奇心又被激发了. 今天下午在Mac OS X上体验了一下ASP.NET 5,而且借助Y ...

  9. mongodb(Index)

    备忘mongoDb 索引的一些知识点. 1.索引是用以加速数据库查询的手段,在mongo中主要是采用B树的方式: 2.每个集合最多可增加64个索引,不建议增加过多索引,原因在于一是索引本身占用空间,二 ...

  10. Java IO3:字节流

    流类 Java的流式输入/输出是建立在四个抽象类的基础上的:InputStream.OutputStream.Reader.Writer.它们用来创建具体的流式子类.尽管程序通过具体子类执行输入/输出 ...