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 Queue模块详细介绍及实例
Dec 27 Python
Python实现完整的事务操作示例
Jun 20 Python
Django权限机制实现代码详解
Feb 05 Python
python 读取摄像头数据并保存的实例
Aug 03 Python
Python符号计算之实现函数极限的方法
Jul 15 Python
Python 一键获取百度网盘提取码的方法
Aug 01 Python
django项目环境搭建及在虚拟机本地创建django项目的教程
Aug 02 Python
Python常用模块logging——日志输出功能(示例代码)
Nov 20 Python
Python使用Matlab命令过程解析
Jun 04 Python
通过代码实例了解Python sys模块
Sep 14 Python
python Matplotlib模块的使用
Sep 16 Python
一些让Python代码简洁的实用技巧总结
Aug 23 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 Global变量定义当前页面的全局变量实现探讨
2013/06/05 PHP
PHP实现数据分页显示的简单实例
2016/05/26 PHP
Laravel 手动开关 Eloquent 修改器的操作方法
2019/12/30 PHP
javascript转换字符串为dom对象(字符串动态创建dom)
2010/05/10 Javascript
javascript 45种缓动效果 非常酷
2011/06/28 Javascript
Javascript面向对象设计一 工厂模式
2011/12/20 Javascript
JavaScript实现带箭头标识的多级下拉菜单效果
2015/08/27 Javascript
JS简单实现DIV相对于浏览器固定位置不变的方法
2016/06/17 Javascript
获取当前月(季度/年)的最后一天(set相关操作及应用)
2016/12/27 Javascript
ionic中列表项增加和删除的实现方法
2017/01/22 Javascript
微信小程序 检查接口状态实例详解
2017/06/23 Javascript
ztree实现左边动态生成树右边为内容详情功能
2017/11/03 Javascript
react redux入门示例
2018/04/19 Javascript
vue组件name的作用小结
2018/05/23 Javascript
WebSocket的简单介绍及应用
2019/05/23 Javascript
Vue+axios+WebApi+NPOI导出Excel文件实例方法
2019/06/05 Javascript
H5实现手机拍照和选择上传功能
2019/12/18 Javascript
[49:21]2018DOTA2亚洲邀请赛3月30日 小组赛B组 Effect VS iG
2018/03/31 DOTA
解决pyqt中ui编译成窗体.py中文乱码的问题
2016/12/23 Python
Django自定义认证方式用法示例
2017/06/23 Python
Python学习笔记之open()函数打开文件路径报错问题
2018/04/28 Python
pycharm中成功运行图片的配置教程
2018/10/28 Python
在python中使用requests 模拟浏览器发送请求数据的方法
2018/12/26 Python
python 模拟登录B站的示例代码
2020/12/15 Python
CAT鞋美国官网:CAT Footwear
2017/11/27 全球购物
Foreo国际站:Foreo International
2018/10/29 全球购物
俄罗斯园林植物网上商店:Garshinka
2020/07/16 全球购物
求最大连续递增数字串(如"ads3sl456789DF3456ld345AA"中的"456789")
2015/09/11 面试题
一百多行代码实现react拖拽hooks
2021/03/23 Javascript
教师队伍管理制度
2014/01/14 职场文书
土地转让协议书
2014/04/15 职场文书
优秀党员自我评价范文
2014/09/15 职场文书
报表员工作失误检讨书范文
2014/09/19 职场文书
公司捐书倡议书
2015/04/27 职场文书
2016年师德师风学习心得体会
2016/01/12 职场文书
MySQL 表锁定 LOCK和UNLOCK TABLES的 SQL语法
2022/04/18 MySQL