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. ios之UIToolBar

    toolbar除了可以和navigationController一起用之外,也可以独立用到view里.工具栏UIToolbar – 一般显示在底部,用于提供一组选项,让用户执行一些功能,而并非用于在完 ...

  2. Python学习笔记3(字典)

    创建字典 dict函数 字典的格式化字符串 字典方法 clear copy fromkeys 序列是一个按照一定顺序将值进行组织的数据结构形式,可以通过索引对其进行征引.另外还有一种数据结构是通过名字 ...

  3. MFC编辑框换行

    字符串结尾加上"\r\n": 编辑框属性设置:Auto HScroll为False,Multiline为True,Want Return为True. =============== ...

  4. Re:从零开始的Linux之路(文件权限)

    基于 Red Hat Enterprise Linux 7.5 或者 CentOS 7.4 基本概念 Linux最核心的一个概念就是:Linux里面任何东西都可以被视为一个文件,包括系统本身(说到底L ...

  5. laravel 设计思想简单了解

    服务容器 laravel框架中 服务容器是整个系统功能调度配置的核心,在系统运行过程中动态的为系统提供需要的服务 从而实现了解耦 控制反转(IOC) 控制反转是一种设计模式 主要解决了系统组件之间的相 ...

  6. 【转】ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

    为了加强安全性,MySQL5.7为root用户随机生成了一个密码,在error log中,关于error log的位置,如果安装的是RPM包,则默认是/var/log/mysqld.log. 一般可通 ...

  7. Hi3519V101 Uboot和Kernel编译

    前面已经搭建好了Ubuntu下的海思开发环境,现在对编译Uboot和Kernel的过程做一个简单的记录.参考文档<Hi3519V101 U-boot 移植应用开发指南.pdf>和<H ...

  8. PAT Basic 1056

    1056 组合数的和 给定 N 个非 0 的个位数字,用其中任意 2 个数字都可以组合成 1 个 2 位的数字.要求所有可能组合出来的 2 位数字的和.例如给定 2.5.8,则可以组合出:25.28. ...

  9. ctci(1)

    // // main.cpp // proj1 // // Created by Yuxin Kang on 8/24/14. // Copyright (c) 2014 Yuxin Kang. Al ...

  10. 《C#高级编程》笔记系列第三弹

    我们在开发WinForm时,经常会看到partial关键字,比如,我们新建一个Windows Form时,后台代码自动添加如下: 1 public partial class Form1 : Form ...