为什么总是在__new __()之后调用__init __()? [英] Why is __init__() always called after __new__()?
问题描述
我只是想简化我的一门课,并以与 flyweight设计模式。
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern.
但是,为什么总是 __ init __
有点困惑在 __ new __
之后调用。我没想到这一点。谁能告诉我为什么会这样,否则我如何实现此功能? (除了将实现放到 __ new __
中,这感觉很hacky。)
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.)
这里有个例子:
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()
输出:
NEW
INIT
EXISTS
INIT
EXISTS
INIT
为什么?
推荐答案
使用
__new __
,当您需要控制
创建新实例时。
Use
__new__
when you need to control the creation of a new instance.
当您需要控制新的初始化时,请使用
__ init __
Use
__init__
when you need to control initialization of a new instance.
__ new __
是实例创建的第一步。首先被称为,是
负责返回您班级的新
实例。
__new__
is the first step of instance creation. It's called first, and is
responsible for returning a new
instance of your class.
相反,
__ init __
不返回任何内容;
In contrast,
__init__
doesn't return anything; it's only responsible for initializing the
instance after it's been created.
通常,您不需要
覆盖 __ new __
,除非您将
子类化为不可变类型,例如
str,int,unicode或tuple。
In general, you shouldn't need to
override __new__
unless you're
subclassing an immutable type like
str, int, unicode or tuple.
从2008年4月发布:何时在mail.python.org上使用 __ new __
与 __ init __
?。
From April 2008 post: When to use __new__
vs. __init__
? on mail.python.org.
您应考虑通常要使用工厂,这是最好的方法。使用 __ new __
并不是一个好的解决方案,因此请考虑使用工厂。在这里,您有一个很好的工厂示例。
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 you have a good factory example.
这篇关于为什么总是在__new __()之后调用__init __()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!