Python中的__new__與__init__魔術方法理解筆記_python

來源:互聯網
上載者:User

很喜歡Python這門語言。在看過文法後學習了Django 這個 Web 開發架構。算是對 Python 有些熟悉了。不過對裡面很多東西還是不知道,因為用的少。今天學習了兩個魔術方法:__new__ 和 __init__。

開攻:

如果對 Python 有所簡單瞭解的話應該知道它包含類這個概念的。文法如下:

複製代碼 代碼如下:

class ClassName:
    <statement - 1>:
        .
        .  
        .
    <statement - N>

問題來了。像我們學習的 C# 或是 Java 這些語言中,聲明類時,都是有建構函式的。類似下面這樣子:

複製代碼 代碼如下:

public class ClassName{
    public ClassName(){

    }
}

當然存取修飾詞不一定非得 public ,這不是重點就不囉嗦了。那 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 的做法我更喜歡。

結束:

今天算是又學習到了新知識,自己挺開心的。再實踐實踐。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.