本文所有实例代码在python3.7下

一.__new__和__init__区别

1.__new__先于__init__执行;__new__是相当于其他OOP语言的构造方法,负责创建实例;之后,__init__负责初始化实例属性。__new__处理对象创建,__ init__处理对象初始化。

2.__new__是一个特殊的静态方法(没有使用装饰器 @staticmethod);由python解释器调用,如果该类没有__new__,则调用父类的__new__.

3.如果我们创建一个类的实例,代码如下:

class Foo:
def __new__(cls, *args, **kwargs):
return super().__new__(cls) def __init__(self, x, y):
self.__x = x
self.__y = y foo = Foo(10, 20)

  

__init__返回为None;
__new__返回了一个创建的实例,其后作为__init__中的self传入

4.通过__new__创建实例,通常是

super().__new__(cls)

# cls为当前要创建的类

5.如果__new__返回它自己的类的实例,那么将使用实例作为第一个被调用的__init__方法的self参数,__init__将隐式调用。
如果__new__方法返回除这个类之外的其他实例,则不会调用实例__init__方法。在这种情况下,您必须自己调用__init__方法。

看一个返回类实例之外的例子:

class Foo:
def __init__(self, x):
self.__x = x @property
def x(self):
return self.__x class Bar:
def __new__(cls, *args, **kwargs):
foo = super().__new__(Foo)
foo.__init__(*args, **kwargs)
return foo bar = Bar(10)
print(bar.x)

  

看一个返回自身类实例的:

class Bar:
def __new__(cls, *args, **kwargs):
foo = super().__new__(cls)
return foo def __init__(self, x):
self.__x = x @property
def x(self):
return self.__x bar = Bar(10)
print(bar.x)

  

二.__new__的一些用途

大多数情况下都不需要重写__new__。

1.单例模式:

class Foo:
__instance = None
def __new__(cls, *args, **kwargs):
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance foo1 = Foo()
foo2 = Foo()
print(foo1, foo2)

  

输出:
<__main__.Foo object at 0x0000029A4B879048> <__main__.Foo object at 0x0000029A4B879048>
可以看出foo1和foo2是同一个实例

2.限制实例的创建数量:

class Foo:
__instance = []
limit = 2
def __new__(cls, *args, **kwargs):
print(len(cls.__instance))
if len(cls.__instance) == cls.limit:
raise RuntimeError("Count not create instance. Limit %s reached" % cls.limit)
instance = super().__new__(cls)
cls.__instance.append(instance)
return instance def __del__(self):
self.__instance.remove(self) foo1 = Foo()
foo2 = Foo()
print(foo1, foo2)

  

3.自定义实例创建

您可以自定义创建的实例,并在调用初始化程序__init__之前对其进行一些操作。此外,您可以基于某些约束对实例创建施加限制

def is_create():
#根据条件判断是否可以创建
return True class Foo:
def __new__(cls, a, b):
if not is_create():
raise RuntimeError('实例不能被创建')
instance = super().__new__(cls)
instance.count = a + b
return instance def __init__(self, a, b):
pass foo = Foo(1, 2)
print(foo.count)

  

4.自定义返回的对象

通常,当您实例化类时,它将返回该类的实例。您可以自定义此行为,并且可以返回所需的对象。

class Foo:
def __new__(cls, a, b):
instance = super().__new__(cls)
instance.__init__(a, b)
return a + b
def __init__(self, a, b):
print('a+b') foo = Foo(1, 2)
print(foo)

  

如果我们不从__new__方法返回实例对象,则必须显式调用__init__。

python的__init__和__new__的更多相关文章

  1. python 的__init__ 和__new__ 区别

    在此介绍一下  __init__ 和  __new__ 先后调用的区别 代码如下: # __init__ 和 __new__的区别 # 通常在编代码时,__init__ 较为常见,但是__new__却 ...

  2. Python中__init__和__new__的区别详解

    __init__ 方法是什么? 使用Python写过面向对象的代码的同学,可能对 __init__ 方法已经非常熟悉了,__init__ 方法通常用在初始化一个类实例的时候.例如: # -*- cod ...

  3. python中__init__()、__new__()、__call__()、__del__()几个魔法方法的用法

    关于__new__()的用法参考: http://www.myhack58.com/Article/68/2014/48183.htm 正文: 一.__new__()的用法: __new__()是在新 ...

  4. python中__init__()、__new__()、__call__()、__del__()用法

    关于__new__()的用法参考: http://www.myhack58.com/Article/68/2014/48183.htm 正文: 一.__new__()的用法: __new__()是在新 ...

  5. python中__init__和__new__的区别

    参考:https://my.oschina.net/liuyuantao/blog/747164 python中__metaclass的详解 参考:https://www.cnblogs.com/ia ...

  6. python中的__init__ 、__new__、__call__小结

    这篇文章主要介绍了python中的__init__ .__new__.__call__小结,需要的朋友可以参考下 1.__new__(cls, *args, **kwargs)  创建对象时调用,返回 ...

  7. 详解python中的__init__与__new__方法

    一.__init__和__new__方法执行的顺序? 在面向对象中介绍了关于对象创建的过程,我们知道__new__方法先于__init__方法执行. 二.__new__方法是什么? 首先,我们先来看下 ...

  8. Python中的__init__和__new__

    一.__init__ 方法是什么? 使用Python写过面向对象的代码的同学,可能对 __init__ 方法已经非常熟悉了,__init__ 方法通常用在初始化一个类实例的时候.例如: # -*- c ...

  9. python中的__init__和__new__的区别

    一.__init__ 方法是什么?(init前后的线是双下划线) 使用Python写过面向对象的代码的同学,可能对 __init__ 方法已经非常熟悉了,__init__ 方法通常用在初始化一个类实例 ...

随机推荐

  1. Linux操作命令(四)

    本次实验将介绍 Linux 命令中 which.whereis.locate 命令的用法. which whereis locate 1.which which命令的作用是,在PATH变量指定的路径中 ...

  2. hh:mm:ss时间格式那些事儿

    怎么把hh:mm:ss.45 时间格式换算成秒? 比较简单点的格式,比如hh:mm:ss是比较容易的,但是怎么样把hh:mm:ss.45,这样的格式,就是秒不是整数的时间格式换算成秒? ans:将时间 ...

  3. JavaWeb中常见的乱码处理(亲测)

    常见编码方式: ISO-8859-1  西欧码 GB2312  简体中文码 GBK   大五码 UTF-8 全球码(推荐) 1.页面(HTML,JSP,Servlet) <%@ page lan ...

  4. Funny Car Racing CSU - 1333 (spfa)

    There is a funny car racing in a city with n junctions and m directed roads. The funny part is: each ...

  5. 【UVA 11077】 Find the Permutations (置换+第一类斯特林数)

    Find the Permutations Sorting is one of the most used operations in real life, where Computer Scienc ...

  6. Java 线程池的实现

    http://blog.csdn.net/iterzebra/article/details/6758481 http://blog.sina.com.cn/s/blog_4914a33b010118 ...

  7. [BZOJ 2298] Problem A

    Link: BZOJ 2298 传送门 Solution: 可以将每个人的话转化为$[l[i],r[i]]$的人得分相同 用$map$记录认为$[i,j]$相同的人数,$pos[i][j]$记录以$i ...

  8. HDU 2255 奔小康赚大钱(KM算法)

    [题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=2255 [题目大意] 求最大匹配 [题解] KM模板 [代码] #include <cstdi ...

  9. [AGC026B]rng_10s

    题意:一个商店,第一天早上有$A$罐苹果汁,一个人每天上午都会来买$B$罐,每天晚上如果剩余罐数$\leq C$那么会增加$D$罐,问能否无限买 收集一个套路...? 首先如果$B\gt A$或者$B ...

  10. 【二分图】【并查集】XVII Open Cup named after E.V. Pankratiev Stage 14, Grand Prix of Tatarstan, Sunday, April 2, 2017 Problem L. Canonical duel

    给你一个网格(n<=2000,m<=2000),有一些炸弹,你可以选择一个空的位置,再放一个炸弹并将其引爆,一个炸弹爆炸后,其所在行和列的所有炸弹都会爆炸,连锁反应. 问你所能引爆的最多炸 ...