new 在新式类中负责真正的实例化对象,而__init__只是负责初始化 __new__创建的对象。一般来说 new 创建一个内存对象,也就是实例化的对象的实体,交给__init__进行进一步加工。官方文档如下:

https://docs.python.org/2/reference/datamodel.html#object.new

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.

这里有几条非常重要

  1. new 接受的参数除了 cls 还可以有很多。 剩余的参数其实是会传递给__init__
  2. new 返回的对象是 cls 的实例,才会调用__init__ 否则就不调用了。

知道了以上信息,我们可以写一个proxy类, 该类的作用是代理其它任何类。 比如:

proxy = Proxy(apple)

我们这里接受了一个对象apple作为参数,那么proxy 就应该有apple的所有属性。 实现方式如下:

首先定义一个类,new 方法会接受 cls, target, *args, **kwargs为参数。这里cls 就是Proxy自己,但我们在真正实例化对象的时候用target的类来实例化。

class Proxy(object):
def __new__(cls, target, *args, **kwargs):
return target.__class__(*args, **kwargs)

接下来定义两个类,有自己的方法

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()

__new__ 和 __init__的更多相关文章

  1. Python中的__new__和__init__

    Python中的__new__和__init__ 写了这么多的class,现在才知道还有个__new__方法, 那么它和__init__有什么区别呢? class TestCls(): "& ...

  2. 飘逸的python - __new__、__init__、__call__傻傻分不清

    __new__: 对象的创建,是一个静态方法.第一个參数是cls.(想想也是,不可能是self,对象还没创建,哪来的self) __init__ : 对象的初始化, 是一个实例方法,第一个參数是sel ...

  3. Python中__new__和__init__区别

    __new__:创建对象时调用,会返回当前对象的一个实例 __init__:创建完对象后调用,对当前对象的一些实例初始化,无返回值 1.在类中,如果__new__和__init__同时存在,会优先调用 ...

  4. 1.(python)__new__与__init__

    1.来比较一下__new__与__init__: (1)__new__在初始化实例前调用,__init__在初始化实例之后调用,用来初始化实例的一些属性或者做一些初始操作 # -*- coding: ...

  5. __new__、__init__、__call__三个特殊方法

    用双下划线包围的特殊方法在Python中又被成为魔术方法,类似于C++等语言中的构造函数,这里我们就来详解Python中的__new__.__init__.__call__三个特殊方法: 1.__ne ...

  6. python中的__new__与__init__,新式类和经典类(2.x)

    在python2.x中,从object继承得来的类称为新式类(如class A(object))不从object继承得来的类称为经典类(如class A()) 新式类跟经典类的差别主要是以下几点: 1 ...

  7. python 中的__new__与__init__

    在Python中的class中有两个方法__new__与__init__,有什么区别呢? class TestCls(): """docstring for TestCl ...

  8. Python系列之 __new__ 与 __init__

    很喜欢Python这门语言.在看过语法后学习了Django 这个 Web 开发框架.算是对 Python 有些熟悉了.不过对里面很多东西还是不知道,因为用的少.今天学习了两个魔术方法:__new__ ...

  9. python中的__new__、__init__和__del__

    __new__.__init__.__del__三个方法用于实例的创建和销毁,在使用python的类中,我们最常用的是__init__方法,通常称为构造方法,__new__方法几乎不会使用,这篇文章是 ...

  10. Python 中的__new__和__init__的区别

    [同] 二者均是Python面向对象语言中的函数,__new__比较少用,__init__则用的比较多. [异] __new__是在实例创建之前被调用的,因为它的任务就是创建实例然后返回该实例对象,是 ...

随机推荐

  1. Mac电脑怎么显示隐藏文件、xcode清除缓存

    1.删除Xcode中多余的证书provisioning profile 手动删除: Xcode6 provisioning profile path: ~/Library/MobileDevice/P ...

  2. swift中使用sqlite3

    import Foundation /** 1. 打开数据库 2. 如果没有数据表,需要首先创表 3. 数据操作 */ class SQLite { var db: COpaquePointer = ...

  3. OpenWrt 路由器如何让 lan 口主机获得 ipv6 网络访问 -- 知乎

    本文转自知乎: OpenWrt 路由器如何让 lan 口主机获得 ipv6 网络访问? - mistforest的回答 - 知乎https://www.zhihu.com/question/29667 ...

  4. Linux进程通信之共享内存实现生产者/消费者模式

    共享内存 共享内存是内核为进程创建的一个特殊内存段,它将出现在进程自己的地址空间中,其它进程可以将同一段共享内存连接(attach)到自己的地址空间.这是最快的进程间通信方式,但是不提供任何同步功能( ...

  5. GIMP模板选区操作

    选择方法有很多种,这里我就新学的方法记录一下,主要是通过小剪刀和Toggle Quick Mask 相结合的运用. 选择Scissors Select Tool工具 设置基本的属性:Antialisa ...

  6. GIMP模版的制作

    GIMP自定模版,方便自己作图 新建模版: 设置开机自动加载模版:

  7. Django之学员管理一

    Django之学员管理一 建表结构: #班级表class: id title 1 五年一班 2 五年二班 3 五年三班 4 五年四班 #学生表student: id name 班级ID(FK外键) 1 ...

  8. python中set()函数的用法

    set顾名思义是集合,里面不能包含重复的元素,接收一个list作为参数 list1=[1,2,3,4] s=set(list1) print(s) #逐个遍历 for i in s: print(i) ...

  9. menu JPopupMenu JTabbedPane

    菜单是GUI中最常用的组件,菜单不是Component类的子类,不能放置在普通容器中,不受布局管理器的约束,只能放置在菜单栏中. 菜单组件由菜单栏 (MenuBar).菜单(Menu)和菜单项(Men ...

  10. tabel使用总结

    对日常使用到的tabel做下记录: <table cellspacing="0"><!--单元格间距为零 默认为2 border默认为 0--> <t ...