python中_new_跟_init_的区别,2.X版本中object.call_的机制是什么

python中__new__和__init__的区别,2.X版本中object.__call__的机制是什么?
class B(object):
  def __new__(cls, *args, **kwds):
    print "three"
    print cls
    print B
    print "B.__new__", args, kwds
    return object.__new__(cls, *args, **kwds)
  def __init__(cls, *args, **kwds):
    print "four"
    print "B.__init__", args, kwds

class A(object):
  def __new__(cls, *args, **kwds):
    print "one"
    print "A.__new__", args, kwds
    return object.__new__(B, *args, **kwds)
  def __init__(cls, *args, **kwds):
    print "two"
    print "A.__init__", args, kwds


print A()
print "====================="
print B()


输出如下:
one
A.__new__ () {}
<__main__.B object at 0x027F3DD0>
=====================
three
<class '__main__.B'>
<class '__main__.B'>
B.__new__ () {}
four
B.__init__ () {}
<__main__.B object at 0x027F3CF0>

我的疑问是:为什么执行这条语句
return object.__new__(B, *args, **kwds)
之后,A.__init__没有被自动调用?
------解决思路----------------------
1. 这类关于语言定义的问题,最好看语言自己的文档:

object.__new__(cls[, ...])
Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).

Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

__new__的作用是批地皮(memory)。__init__的作用是在分给你的地皮上进行初期建设,加上合适的建筑(data)。一般来说,地皮批划给你后,会自动派施工队按你申请的地皮类型进行初期建设(你的例子中B()的情况)。上面红色的部分说如果给你的地皮不是你申请的类型(通过cls参数指定),那么新地皮上的初期建设就不会自动执行(大概是因为无论是自动执行A.__init__或是B.__init__,都不一定是最好的选择)

2. __call__的文档在同一网页上:

object.__call__(self[, args...])
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

(试着解释了一下,但看起来就像把上面的文档翻译了一遍,可见上面的文档就说明了一切了,自己看吧)。

3. 

  def __init__(cls, *args, **kwds):
    print "two"
    print "A.__init__", args, kwds

最后,虽然cls,self的名字都是约定俗成,而不是法律要求,你用其它名字也可以。但一般__init__的第一个参数叫self,尤其不该叫cls。
------解决思路----------------------
说起来文字太多,你可以参考下
http://www.jb51.net/article/48044.htm