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之私有函数和专有方法
Oct 24 Python
Python中使用wxPython开发的一个简易笔记本程序实例
Feb 08 Python
Python max内置函数详细介绍
Nov 17 Python
Sanic框架基于类的视图用法示例
Jul 18 Python
PyCharm鼠标右键不显示Run unittest的解决方法
Nov 30 Python
Python常用的json标准库
Feb 19 Python
python图形用户接口实例详解
Dec 16 Python
Python类继承和多态原理解析
Feb 05 Python
如何提高python 中for循环的效率
Apr 15 Python
idea2020手动安装python插件的实现方法
Jul 17 Python
最新pycharm安装教程
Nov 18 Python
python 窃取摄像头照片的实现示例
Jan 08 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
php提示无法加载或mcrypt没有找到 PHP 扩展 mbstring解决办法
2012/03/27 PHP
基于xcache的配置与使用详解
2013/06/18 PHP
解析php中用PHPMailer来发送邮件的示例(126.com的例子)
2013/06/24 PHP
教你如何快捷的使用cmd访问mysql小技巧
2014/05/26 PHP
php遍历目录方法小结
2015/03/10 PHP
php常用字符函数实例小结
2016/12/29 PHP
PHP中TP5 上传文件的实例详解
2017/07/31 PHP
基于jquery的15款幻灯片插件
2011/04/10 Javascript
js给dropdownlist添加选项的小例子
2013/03/04 Javascript
from表单多个按钮提交用onclick跳转不同action
2014/04/24 Javascript
javascript模拟实现ajax加载框实例
2014/10/15 Javascript
js实现各种复制到剪贴板的方法(分享)
2016/10/27 Javascript
Bootstrap基本组件学习笔记之导航(10)
2016/12/07 Javascript
nodejs入门教程五:连接数据库的方法分析
2017/04/24 NodeJs
Vue服务器渲染Nuxt学习笔记
2018/01/31 Javascript
node中的密码安全(加密)
2018/09/17 Javascript
微信小程序实现上传word、txt、Excel、PPT等文件功能
2019/05/23 Javascript
vue动态配置模板 'component is'代码
2019/07/04 Javascript
vue集成openlayers加载geojson并实现点击弹窗教程
2020/09/24 Javascript
python3之微信文章爬虫实例讲解
2017/07/12 Python
Python reduce()函数的用法小结
2017/11/15 Python
python 矩阵增加一行或一列的实例
2018/04/04 Python
通过python的matplotlib包将Tensorflow数据进行可视化的方法
2019/01/09 Python
python里 super类的工作原理详解
2019/06/19 Python
浅析PEP570新语法: 只接受位置参数
2019/10/15 Python
Python反爬虫伪装浏览器进行爬虫
2020/02/28 Python
python相对企业语言优势在哪
2020/06/12 Python
Room Mate Hotels美国:西班牙酒店品牌
2018/04/10 全球购物
英国户外服装品牌:Craghoppers
2019/04/25 全球购物
《红军不怕远征难》教学反思
2014/04/14 职场文书
搞笑车尾标语
2014/06/23 职场文书
音乐学专业求职信
2014/07/22 职场文书
民主评议政风行风整改方案
2014/09/17 职场文书
交通事故案件代理词
2015/05/23 职场文书
2016教师国培研修感言
2015/12/08 职场文书
一小时学会TensorFlow2之基本操作2实例代码
2021/09/04 Python