68

深入理解Python中的 __new__ 和 __init__

 5 years ago
source link: http://sunlogging.com/2018/09/15/深入理解python中的-__new__-和-__init__/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文为译文,原文链接: https://spyhce.com/blog/understanding-new-and-init

本文的目的是讨论Python中 __new__ 和 __ini___ 的用法。 __new__ 和 __init__ 的区别主要表现在:1. 它自身的区别;2. 及在Python中新式类和老式类的定义。

理解 __new__ 和 __init__ 的区别

这两个方法的主要区别在于:__new__ 负责对象的创建而 __init__ 负责对象的初始化。在对象的实例化过程中,这两个方法会有些细微的差别,表现于:如何工作,何时定义。

Python中两种类的定义方式

Python 2.x 中类的定义分为新式定义和老式定义两种。老式的类出现在Python 3之前且定义时不继承自’object’ 基类,默认是继承自’type’ :而新式类在定义时显示地继承’object’类。

Python 2.x中老式类的定义:

class A:  # -> inherits from  type 
    pass

Python 2.x中新式类的定义:

class A(object):  # -> clearly inherits from  object 
    pass

在Python 3.x中没有新式类和老式类之分,它们都继承自’object’ 类。因此可以不用显示地指定其基类。’object’基类中拥有的方法和属性可通用于所有的新式类。

下文中我们将通过测试 __new__ 和 __init__ 在各个case中的用法,来逐步剖析它们的功能和区别,并以此确实我们该如何使用它们。

分析不同的Case

在研究具体的实现之前,我们应该知道 __new__ 方法只接受 cls 作为它的第一个参数,而 __init__ 一个参数是 self (__new__ 是一个类方法,而__init__ 是一个对象方法)。因为我们调用 __new__ 之前连实例都还没有,因此那时根本没有 self 的存在。__init__ 在 使用 __new__ 创建并返回一个实例之后调用,因此可将返回的实例通过self传递给它。

老式类中的__new__ 和 __init__

老式类中其实并没有 __new__ 方法,因为 __init__ 就是它的构造方法(函数)。因此如果我们有下面这段代码:

class A:

    def __new__(cls):
        print "A.__new__ is called"  # -> this is never called

A()

这个case中的 __new__ 方法将永远不会执行,因为它不是老式类的目标函数。

如果我们是重写一个__init__ 方法:

class A:

    def __init__(self):
        print "A.__init__ called"

A()

它将会输出:

A.__init__ called

我们尝试从 __init__ 方法中返回一个值:

class A:

    def __init__(self):
        return 29

A()

将会产生一个错误:

TypeError: __init__() should return None​

这意味着我们实例化一个老式类的对象时,不能控制它返回什么内容。

新式类中的 __new__ 和 __init__

新式类允许开发者根据他们的意图来重写 __new__ 和 __init__ 方法。__new__ (构造函数)单独地创建一个对象,而 __init__ (初始化函数)负责初始化这个对象。

我们看一下下面这个case的执行顺序:

class A(object):  # -> don t forget the object specified as base

    def __new__(cls):
        print "A.__new__ called"
        return super(A, cls).__new__(cls)

    def __init__(self):
        print "A.__init__ called"

A()

将会输出:

A.__new__ called
A.__init__ called

你可能想要问 __init__ 和 __new__ 是在哪里被调用的,我能告诉你的是: __new__ 是在我们调用类名进行实例化时自动调用的,__init__ 是在这个类的每一次实例化对象之后调用的,__new__ 方法创建一个实例之后返回这个实例对象并传递给 __init__ 方法的 self 参数。因此,即使你将创建的实例对象保存成一个全局或静态的变量,并且每次调用__new__ 方法时都返回这个对象,__init__ 方法依然每次都会被调用。这意味着如果我们在 __new__ 中省略调用基类的super(A, cls).__new__(cls) 代码,__init__ 方法将不会被执行。我们一起看一下这个case的代码:

class A(object):

    def __new__(cls):
        print "A.__new__ called"

    def __init__(self):
        print "A.__init__ called"  # -> is actually never called

print A()

输出的内容如下:

A.__new__ called
None

Obviously the instantiation is evaluated to None since we don’t return anything from the constructor.

显然这个实例被认定None,如果我们没有在构造函数中返回任何对象。

想像一下,如果我们从 __new__ 中返回一些其他东西(对象)将会发生什么,如下面这样:

class A(object):

    def __new__(cls):
        print "A.__new__ called"
        return 29

print A()

猜想会输出如下的内容:

A.__new__ called
29

我们再看一下从 __init__ 中返回一个对象将会发生什么:

class A(object):

    def __init__(self):
        print "A.__init__ called" 
            return 33  # -> TypeError: __init__ should return None

A()

这将会出现警告:

TypeError: __init__ should return None

在调用 __init__ 时会出现一个TypeError的异常:__init__() should return None, not ‘int’。这主要是因为 __init__ 的作用只是刷新和更改刚创建的这个实例对象的状态。

新式的类在灵活性上提供了更多的功能,允许我们在构造和初始化的级别做更多预处理和后处理的操作,让我们可以在实例化时控制我们想要返回的内容。

考虑到这一点,我们尝试一下在 __new__ 中返回一个其他类的对象。

首先,我们定义一个待用的类:

class Sample(object):

    def __str__(self):
        return "SAMPLE"

然后,再定义一个重写 __new__ 方法的类:

class A(object):

    def __new__(cls):
        return Sample()

也可以写成下面这样:

class A(object):

    def __new__(cls):
        return super(A, cls).__new__(Sample)

最后,我们调用A()来创建一个对象,并打印该对象:

print A()

这将会输出:

SAMPLE

参考资料

https://docs.python.org/2/library/functions.html#object

http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html#the-object-within

https://wiki.python.org/moin/NewClassVsClassicClass


Recommend

  • 119
    • down.51cto.com 6 years ago
    • Cache

    深入理解Python

    市面上不乏python入门教程,但深入讲解python语言和应用的课程甚少,本课程定位深入理解python核心语法,结合实际应用场景,带领初学python或是有其它编程语言背景的程序员能快速掌握这门强大的语言,使其能在开发中发挥强大的..

  • 75
    • developer.51cto.com 6 years ago
    • Cache

    带你深入理解Python字符编码

    滑动验证页面 别离开,为了更好的访问体验,请滑动滑块进行验证,通过后即可继...

  • 35
    • www.10tiao.com 5 years ago
    • Cache

    深入理解Python中的迭代

    我们先研究一下Python的for循环,看看它们是如何工作的,原理是什么。 Python的for循环与其它语言的for循环用法不一样。在本文中,我们将深入研究Python的...

  • 87
    • www.tuicool.com 4 years ago
    • Cache

    深入理解Python中的asyncio

    asyncio介绍 熟悉c#的同学可能知道,在c#中可以很方便的使用 async 和 await 来实现异步编程,那么在python中应该怎么做呢,其实python也支持异步编程,一般使用 asyncio 这个库,下...

  • 12
    • www.cnblogs.com 4 years ago
    • Cache

    深入理解new运算符

    在 JavaScript 中,new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。创建一个对象很简单,为什么我们还要多此一举使用 new 运算符呢?它到底有什么样的魔力? 认识 new 运算符 通过下面的例...

  • 8
    • www.pythonpodcast.com 3 years ago
    • Cache

    The Python Podcast.__init__

    Turning Notebooks Into Collaborative And Dynamic Data Applications With Hex - Episode 294 December 21, 2020

  • 6

    由于《深入理解Android 卷一》和《深入理解Android卷二》不再出版,而知识的传播不应该因为纸质媒介的问题而中断,所以我将在CSDN博客中全文转发这两本书的全部内容。 第3章  深入理解init 本章主要内容 ·  深入分析i...

  • 0

    <七>深入理解new和delete的原理 new ,delete 运...

  • 4

    When developing multiple python packages and codes, or working with multiple directories, we often come across the __ init __.py file in Python programming language. In this article, we will learn, what is __ init __.py f...

  • 1
    • cr.openjdk.org 8 months ago
    • Cache

    new/dup/init: The Dance Goes On

    The Dance Goes On new/dup/init: The Dance Goes On John Rose, 2023-0814 (“what about”s and other adjustments are solicited)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK