我只是想简化我的一个类,并引入了一些与 享元设计模式 风格相同的功能。
但是,我有点困惑为什么 __init__
总是在 __new__
之后调用。我没想到会这样。谁能告诉我为什么会这样,否则我该如何实现这个功能? (除了将实现放入 __new__
感觉很老套。)
这是一个例子:
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
为什么?
原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议
来自 2008 年 4 月的帖子: 何时使用
__new__
与__init__
? 在 mail.python.org 上。您应该考虑到您尝试做的事情通常是通过 工厂 完成的,这是最好的方法。使用
__new__
不是一个好的清洁解决方案,因此请考虑使用工厂。这是一个很好的例子: ActiveState Fᴀᴄᴛᴏʀʏ ᴘᴀᴛᴛᴇʀɴ Recipe 。