为什么 __init__() 总是在 __new__() 之后调用? [英] Why is __init__() always called after __new__()?
问题描述
我只是想简化我的一个类,并以与 相同的风格引入了一些功能享元设计模式.
然而,我有点困惑为什么 __init__
总是在 __new__
之后被调用.我没想到这一点.谁能告诉我为什么会发生这种情况以及我如何才能实现此功能?(除了将实现放入 __new__
中,这感觉很hacky.)
这是一个例子:
A 类(对象):_dict = dict()def __new__(cls):如果 A._dict 中的键":打印存在"返回 A._dict['key']别的:打印新"返回 super(A, cls).__new__(cls)def __init__(self):打印初始化"A._dict['key'] = self打印 ""a1 = A()a2 = A()a3 = A()
输出:
NEW在里面存在在里面存在在里面
为什么?
在需要控制时使用
__new__
创建新实例.
<块引用>
使用__init__
当您需要控制新实例的初始化时.
__new__
是实例创建的第一步.它首先被调用,并且是负责退回一个新的类的实例.
<块引用>
相比之下,__init__
不返回任何内容;它只负责初始化实例创建后.
一般来说,您不需要覆盖 __new__
除非你子类化一个不可变类型,如str、int、unicode 或元组.
来自 2008 年 4 月的帖子:何时使用 __new__
vs. __init__
? 在 mail.python.org 上.
您应该考虑到您尝试执行的操作通常是通过 Factory 完成的,那就是最好的方法来做到这一点.使用 __new__
不是一个好的干净的解决方案,所以请考虑使用工厂.这是一个很好的例子:ActiveState Fᴀᴄᴛᴏʀʏ ᴘᴀᴛᴛᴇʀɴ食谱.
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
However, I'm a bit confused as to why __init__
is always called after __new__
. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__
which feels quite hacky.)
Here's an example:
class A(object):
_dict = dict()
def __new__(cls):
if 'key' in A._dict:
print "EXISTS"
return A._dict['key']
else:
print "NEW"
return super(A, cls).__new__(cls)
def __init__(self):
print "INIT"
A._dict['key'] = self
print ""
a1 = A()
a2 = A()
a3 = A()
Outputs:
NEW
INIT
EXISTS
INIT
EXISTS
INIT
Why?
Use
__new__
when you need to control the creation of a new instance.
Use
__init__
when you need to control initialization of a new instance.
__new__
is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.
In contrast,
__init__
doesn't return anything; it's only responsible for initializing the instance after it's been created.In general, you shouldn't need to override
__new__
unless you're subclassing an immutable type like str, int, unicode or tuple.
From April 2008 post: When to use __new__
vs. __init__
? on mail.python.org.
You should consider that what you are trying to do is usually done with a Factory and that's the best way to do it. Using __new__
is not a good clean solution so please consider the usage of a factory. Here's a good example: ActiveState Fᴀᴄᴛᴏʀʏ ᴘᴀᴛᴛᴇʀɴ Recipe.
这篇关于为什么 __init__() 总是在 __new__() 之后调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!