new 在新式類中負責真正的實例化對象,而__init__只是負責初始化 __new__建立的對象。通常來講 new 建立一個內存對象,也就是實例化的對象的實體,交給__init__進行進一步加工。官方文檔以下:html
https://docs.python.org/2/reference/datamodel.html#object.__new__python
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.
這裏有幾條很是重要express
知道了以上信息,咱們能夠寫一個proxy類, 該類的做用是代理其它任何類。 好比:app
proxy = Proxy(apple)
咱們這裏接受了一個對象apple做爲參數,那麼proxy 就應該有apple的全部屬性。 實現方式以下:代理
首先定義一個類,new 方法會接受 cls, target, *args, **kwargs爲參數。這裏cls 就是Proxy本身,但咱們在真正實例化對象的時候用target的類來實例化。code
class Proxy(object): def __new__(cls, target, *args, **kwargs): return target.__class__(*args, **kwargs)
接下來定義兩個類,有本身的方法htm
class A(object): def run(self): return 'run' class B: def fly(self): return 'fly'
能夠看到,咱們能夠用proxy 來代理 a,b 由於proxy在實例化的時候實際上藉助了a/b對象
a = A() b = B() pa = Proxy(a) pb = Proxy(b) print "pa.run is ", pa.run() print "pb.fly is ", pb.fly()