Python使用__new__和__init__? [英] Python's use of __new__ and __init__?

查看:116
本文介绍了Python使用__new__和__init__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想简化我的一个课程,并且引入了一些与相同的样式的功能flyweight设计模式



然而,对于为什么 __ init __ 总是有点困惑在 __新__ 之后调用。我没想到这个任何人都可以告诉我为什么会发生这种情况,否则我如何实现这个功能呢? (除了将实现放在 __ new __ 中,感觉很诡异)。



这里有一个例子:

  class A(object):
_dict = dict()

def __new __(cls)
如果A._dict中的key:
printEXISTS
return A._dict ['key']
else:
printNEW
return super(A,cls).__ new __(cls)

def __init __(self):
printINIT
A._dict ['key'] = self
print

a1 = A()
a2 = A()
a3 = A()
/ pre>

输出:

 
INIT

EXISTS
INIT

EXISTS
INIT

为什么?

解决方案


使用 __新__ 您需要控制
创建一个新的实例。当您需要控制新实例的初始化时,使用
__ init __



__新__ 是第一个实例创建步骤。它被称为第一个,并且
负责返回一个新的
实例的类。相反,
__ init __ 不返回任何东西;它只负责在创建
实例后初始化。



一般来说,您不需要
覆盖 __新__ 除非你是
子类化一个不可变类型,如
str,int,unicode或tuple。


从: http://mail.python.org/pipermail/tutor/ 2008年4月/ 061426.html



您应该考虑到您尝试做的通常是使用工厂,这是最好的方法。使用 __新__ 不是一个很好的干净的解决方案,所以请考虑使用工厂。在这里,您可以一个很好的工厂范例


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 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: http://mail.python.org/pipermail/tutor/2008-April/061426.html

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.

这篇关于Python使用__new__和__init__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆