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 相关文章推荐
pyramid配置session的方法教程
Nov 27 Python
python使用fileinput模块实现逐行读取文件的方法
Apr 29 Python
Python调用SQLPlus来操作和解析Oracle数据库的方法
Apr 09 Python
Windows下安装python2和python3多版本教程
Mar 30 Python
python实现机器人行走效果
Jan 29 Python
python实现csv格式文件转为asc格式文件的方法
Mar 23 Python
Python读写/追加excel文件Demo分享
May 03 Python
在Python中实现shuffle给列表洗牌
Nov 08 Python
PyQt5实现简易计算器
May 30 Python
Python高级编程之消息队列(Queue)与进程池(Pool)实例详解
Nov 01 Python
浅谈Python numpy创建空数组的问题
May 25 Python
python 实现体质指数BMI计算
May 26 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 定界符格式引起的错误
2011/05/24 PHP
PHP实现图片裁剪、添加水印效果代码
2014/10/01 PHP
thinkphp 框架数据库切换实现方法分析
2020/05/18 PHP
asp.net和asp下ACCESS的参数化查询
2008/06/11 Javascript
js中通过父级进行查找定位元素
2014/06/15 Javascript
js实现按钮加背景图片常用方法
2014/11/01 Javascript
Jquery中基本选择器用法实例详解
2015/05/18 Javascript
js电话号码验证方法
2015/09/28 Javascript
jQuery.Callbacks()回调函数队列用法详解
2016/06/14 Javascript
javascript鼠标滑过显示二级菜单特效
2020/11/18 Javascript
jQuery实现自动调用和触发某个事件的方法
2016/11/18 Javascript
JavaScript动态加载重复绑定问题
2018/04/01 Javascript
jQuery实现的自定义轮播图功能详解
2018/12/28 jQuery
vue指令之表单控件绑定v-model v-model与v-bind结合使用
2019/04/17 Javascript
微信小程序工具函数封装
2019/10/28 Javascript
es6函数中的作用域实例分析
2020/04/18 Javascript
angular *Ngif else用法详解
2020/12/15 Javascript
centos 下面安装python2.7 +pip +mysqld
2014/11/18 Python
使用Python编写简单的画图板程序的示例教程
2015/12/08 Python
python实现树形打印目录结构
2018/03/29 Python
解决Python 中英文混输格式对齐的问题
2018/07/16 Python
Python实现将Excel转换成xml的方法示例
2018/08/25 Python
【python】matplotlib动态显示详解
2019/04/11 Python
Flask中endpoint的理解(小结)
2019/12/11 Python
python设置环境变量的作用整理
2020/02/17 Python
Python2.6版本pip安装步骤解析
2020/08/17 Python
详解用 python-docx 创建浮动图片
2021/01/24 Python
芬兰攀岩、山地运动和户外活动用品购物网站:Bergfreunde
2016/10/06 全球购物
什么是托管函数?托管函数有什么用?
2014/06/15 面试题
什么是Connection-oriented Protocol/Connectionless Protocol面向连接的协议/无连接协议
2012/09/06 面试题
日语求职信范文
2013/12/17 职场文书
大学生职业生涯规划书模板
2014/01/03 职场文书
值班管理制度范本
2015/08/06 职场文书
2016入党积极分子党校培训心得体会
2016/01/06 职场文书
golang日志包logger的用法详解
2021/05/05 Golang
MySQL系列之开篇 MySQL关系型数据库基础概念
2021/07/02 MySQL