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通过pil将图片转换成黑白效果的方法
Mar 16 Python
Python argv用法详解
Jan 08 Python
轻松掌握python设计模式之访问者模式
Nov 18 Python
Python微信库:itchat的用法详解
Aug 14 Python
Python生成8位随机字符串的方法分析
Dec 05 Python
Python 修改列表中的元素方法
Jun 26 Python
使用Python实现企业微信的自动打卡功能
Apr 30 Python
Python占用的内存优化教程
Jul 28 Python
jupyter lab文件导出/下载方式
Apr 22 Python
keras 解决加载lstm+crf模型出错的问题
Jun 10 Python
使用pygame实现垃圾分类小游戏功能(已获校级二等奖)
Jul 23 Python
Python图片处理之图片裁剪教程
May 27 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
提取HTML标签
2006/10/09 PHP
php之XML转数组函数的详解
2013/06/07 PHP
Zend Framework教程之Autoloading用法详解
2016/03/08 PHP
PHP根据session与cookie用户登录状态操作类的代码
2016/05/13 PHP
PHP中Cookie的使用详解(简单易懂)
2017/04/28 PHP
iis 7下安装laravel 5.4环境的方法教程
2017/06/14 PHP
调试代码导致IE出错的避免方法
2014/04/04 Javascript
微信小程序 保留小数(toFixed)详细介绍
2016/11/16 Javascript
node.js实现登录注册页面
2017/04/08 Javascript
javascript数据结构之串的概念与用法分析
2017/04/12 Javascript
浅谈Node 调试工具入门教程
2018/03/20 Javascript
Node.js应用设置安全的沙箱环境
2018/04/23 Javascript
浅谈angular2子组件的事件传递(任意组件事件传递)
2018/09/30 Javascript
小程序从手动埋点到自动埋点的实现方法
2019/01/24 Javascript
layui-table获得当前行的上/下一行数据的例子
2019/09/24 Javascript
解决vue.js提交数组时出现数组下标的问题
2019/11/05 Javascript
javascript代码实现简易计算器
2021/01/25 Javascript
[40:55]Liquid vs LGD 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
[03:41]2018完美盛典-《Fight With Us》
2018/12/16 DOTA
python连接MySQL、MongoDB、Redis、memcache等数据库的方法
2013/11/15 Python
qpython3 读取安卓lastpass Cookies
2016/06/19 Python
Python列表list排列组合操作示例
2018/12/18 Python
浅析PyTorch中nn.Module的使用
2019/08/18 Python
Django之路由层的实现
2019/09/09 Python
Python读写文件模式和文件对象方法实例详解
2019/09/17 Python
在Python中通过threshold创建mask方式
2020/02/19 Python
Python必须了解的35个关键词
2020/07/16 Python
Python特殊属性property原理及使用方法解析
2020/10/09 Python
HTML5 创建canvas元素示例代码
2014/06/04 HTML / CSS
瑜伽国际:Yoga International
2018/04/18 全球购物
李维斯法国官网:Levi’s法国
2019/07/13 全球购物
计算机网络专业推荐信
2013/11/24 职场文书
护士岗位求职应聘自荐书范文
2014/02/12 职场文书
私人贷款担保书该怎么写呢?
2019/07/02 职场文书
导游词之丽江普济寺
2019/10/22 职场文书
JVM钩子函数的使用场景详解
2021/08/23 Java/Android