Python中的__new__与__init__魔术方法理解笔记


Posted in Python onNovember 08, 2014

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

开攻:

如果对 Python 有所简单了解的话应该知道它包含类这个概念的。语法如下:

class ClassName:

    <statement - 1>:

        .

        .   

        .

    <statement - N>

问题来了。像我们学习的 C# 或是 Java 这些语言中,声明类时,都是有构造函数的。类似下面这样子:

public class ClassName{

    public ClassName(){
    }

}

当然访问修饰符不一定非得 public ,这不是重点就不??铝恕D Python 中的构造函数是怎样的呢?我自己的理解是它是没有构造函数的。只不过在初始化时会调用一些内部的可被改变的方法。比如:__new__ 和 __init__ 。从字面意思理解 __new__ 应该会在 __init__ 之前执行,实际查了资料后确实是如此的。官方文档中关于 __init__ 方法有这样一句话:

Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__()

意思就是说在创建类时,如果想指定的它的初始状态,那么可以通过定义一个指定名称为 __init__ 的方法去实现这样的功能。这样说来 __new__ 并不是官方推荐的初始化类时要使用的方法。但是 __new__ 却是在 __init__ 之前执行的。官方文档中对 __init__ 介绍的第一句便是:当创建实例时调用 __init__ 方法(Called when the instance is created.),后面又介绍说,如果想调用基类的 __init__方法必须显式的调用,只继承基类在初始化子类时并不会自动调用基类的 __init__ 方法。到此应该算是对 __init__ 方法了解了。

下面我们看一下 __new__ 方法是怎么回事儿。先看一下官方文档:

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.

从这里可以看出来,这个方法才是产生类的实例的地方。当实例创建完成就调用 __init__ 方法,初始化类的内部状态值。文档中还提到 __new__ 方法其实是一个静态方法,不用每次定义类的时候都声明这个方法,因为在版本 2.4 之后 object 是所有对象的基类,而 __new__ 是定义在 object 对象内部的静态方法。

到这儿其实就差不多了,就按字面意思理解就可以。 __new__ 用于创建对象,而 __init__ 是在创建完成之后初始化对象状态。前两天看到一个有趣的方法,通过使用 __new__ 应用了单例模式在对象身上。

注意点:在类继承中,当子类和父类都定义了自己的 __new__ 方法时,那么会先调用子类的 __new__ 方法再调用父类的。这一点倒是和 C# 中的继承是一样的。其实仔细想想 Python 中只不过是把初始化和创建对象这两个概念分开了,而 C# 中即没有这么干,只给了构造函数,开发者可以自己看着办。从这一点儿上说我觉得 Python 的做法我更喜欢。

结束:

今天算是又学习到了新知识,自己挺开心的。再实践实践。。。

Python 相关文章推荐
跟老齐学Python之玩转字符串(2)更新篇
Sep 28 Python
Python 专题六 局部变量、全局变量global、导入模块变量
Mar 20 Python
selenium+python 对输入框的输入处理方法
Oct 11 Python
Python File(文件) 方法整理
Feb 18 Python
浅析python的Lambda表达式
Feb 27 Python
pip指定python位置安装软件包的方法
Jul 12 Python
Django之模板层的实现代码
Sep 09 Python
Python实现桌面翻译工具【新手必学】
Feb 12 Python
Python图像识别+KNN求解数独的实现
Nov 13 Python
基于Python的接口自动化unittest测试框架和ddt数据驱动详解
Jan 27 Python
python如何做代码性能分析
Apr 26 Python
Python+OpenCV实现在图像上绘制矩形
Mar 21 Python
Python使用百度API上传文件到百度网盘代码分享
Nov 08 #Python
python中readline判断文件读取结束的方法
Nov 08 #Python
Python实现基于HTTP文件传输实例
Nov 08 #Python
Python使用urllib模块的urlopen超时问题解决方法
Nov 08 #Python
Python set集合类型操作总结
Nov 07 #Python
数据挖掘之Apriori算法详解和Python实现代码分享
Nov 07 #Python
Python的subprocess模块总结
Nov 07 #Python
You might like
大师制作的中短波矿石收音机
2020/04/02 无线电
一个程序下载的管理程序(一)
2006/10/09 PHP
深入Apache与Nginx的优缺点比较详解
2013/06/17 PHP
Mac系统完美安装PHP7详细教程
2017/06/06 PHP
ajax更新数据后,jquery、jq失效问题
2011/03/16 Javascript
js实现最短的XML格式化工具实例
2015/03/12 Javascript
Backbone.js的一些使用技巧
2015/07/01 Javascript
基于javascript制作经典传统的拼图游戏
2016/03/22 Javascript
基于jquery实现三级下拉菜单
2016/05/10 Javascript
快速解决js动态改变dom元素属性后页面及时渲染的问题
2016/07/06 Javascript
js显示动态时间的方法详解
2016/08/20 Javascript
Bootstrap模态框插件使用详解
2017/05/11 Javascript
浏览器调试动态js脚本的方法(图解)
2018/01/19 Javascript
jQuery实现导航样式布局操作示例【可自定义样式布局】
2018/07/24 jQuery
js+canvas实现验证码功能
2020/09/21 Javascript
JS实现数组深拷贝的方法分析
2019/03/06 Javascript
js实现贪吃蛇小游戏(加墙)
2020/07/31 Javascript
通过实例解析json与jsonp原理及使用方法
2020/09/27 Javascript
python脚本实现查找webshell的方法
2014/07/31 Python
Python实现ping指定IP的示例
2018/06/04 Python
python环形单链表的约瑟夫问题详解
2018/09/27 Python
pandas筛选某列出现编码错误的解决方法
2018/11/07 Python
django echarts饼图数据动态加载的实例
2019/08/12 Python
详解python中的模块及包导入
2019/08/30 Python
AmazeUI中模态框的实现
2020/08/19 HTML / CSS
营业员实习自我鉴定
2013/12/07 职场文书
顶岗实习接收函
2014/01/09 职场文书
初一科学教学反思
2014/01/27 职场文书
超市国庆节促销方案
2014/02/20 职场文书
安全责任书范文
2014/03/12 职场文书
市场营销专业自荐书
2014/06/10 职场文书
商场消防安全责任书
2014/07/29 职场文书
2015年大学迎新工作总结
2015/07/16 职场文书
上手简单,功能强大的Python爬虫框架——feapder
2021/04/27 Python
详解Spring Security中的HttpBasic登录验证模式
2022/03/17 Java/Android
Python内置数据类型中的集合详解
2022/03/18 Python