Python __new__ 、__init__、 __call__

Contains:
  • __new__: 创建对象时调用,返回当前对象的一个实例
  • __init__:创建完成对象后调用,对当前对象的实例的一些初始化,无返回值
  • __call__:

一、__init__通过此方法我们可以顶一个对象的初始操作。
但是当我新建一个类的实例的时候,__init__并不是第一个被调用的,实际上,还有一个叫做__new__的方法,来构造这个实例。然后在给开始创建的初始化函数传递参数。


二、__new__   
   
    @staticmethod # known case of __new__
    def __new__(cls, *more): # known special case of object.__new__

        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """

        pass

__new__方法相当不常用,但是它有自己的特性,特别是当继承一个不可变的类型比如一个tuple或者string.
Q:可是什么时候使用__new__?
难道是这个吗?特别是当继承一个不可变的类型比如一个tuple或者string.
引用

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.

三、__call__

引用
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, ...).


这个方法可以让类的实例的行为表现的像函数一样,你可以调用他们,讲一个函数当做一个参数传到另外一个函数中等等。
class Entity:

    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __call__(self, x, y):
        self.x = x
        self.y = y

entity = Entity(2,3)
print 'before __call__',(entity.x,entity.y)
entity.__call__(4,5)
print 'after __call__',(entity.x,entity.y)

result:
before __call__ (2, 3)
after __call__ (4, 5)

参考资料:
http://docs.python.org/2/reference/datamodel.html
http://stackoverflow.com/questions/8106900/new-and-init-in-python
http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
http://www.wingide.com/psupport/python-manual/2.4/ref/customization.html
http://stackoverflow.com/questions/12971641/need-to-understand-the-flow-of-init-new-and-call?lq=1
http://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/a-guide-to-pythons-magic-methods.html

你可能感兴趣的:(python)