python -- why defined '__new__' and '__init__' all in a class

在学习openstack源码的时候发现一个类里面有'__new__' 和'__init__'两个构造,不知道什么原因,在stackoverflow中找到了满意的解答:

粘贴解答至此:

You can define either or both of __new__ and __init__.

__new__ must return an object -- which can be a new one (typically that task is delegated to type.__new__), an existing one (to implement singletons, "recycle" instances from a pool, and so on), or even one that's not an instance of the class. If __new__ returns an instance of the class (new or existing), __init__ then gets called on it; if __new__ returns an object that's not an instance of the class, then __init__ is not called.

__init__ is passed a class instance as its first item (in the same state __new__ returned it, i.e., typically "empty") and must alter it as needed to make it ready for use (most often by adding attributes).

In general it's best to use __init__ for all it can do -- and __new__, if something is left that __init__ can't do, for that "extra something".

So you'll typically define both if there's something useful you can do in __init__, but not everything you want to happen when the class gets instantiated.

For example, consider a class that subclasses int but also has a foo slot -- and you want it to be instantiated with an initializer for the int and one for the .foo. As int is immutable, that part has to happen in __new__, so pedantically one could code:

>>>class x(int):...def __new__(cls, i, foo):...     self = int.__new__(cls, i)...return self
...def __init__(self, i, foo):...     self.foo = foo
...   __slots__ ='foo',...>>> a = x(23,'bah')>>>print a
23>>>print a.foo
bah
>>>

In practice, for a case this simple, nobody would mind if you lost the __init__ and just moved the self.foo = foo to __new__. But if initialization is rich and complex enough to be best placed in __init__, this idea is worth keeping in mind.

share | improve this answer
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mingjie1212

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值