国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-23 06:08:51
字體:
來源:轉載
供稿:網友

很喜歡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.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黑山县| 冕宁县| 大化| 武陟县| 喀喇沁旗| 彭山县| 凤山县| 金坛市| 鹿泉市| 嘉善县| 绵阳市| 西城区| 涡阳县| 南溪县| 贺州市| 班玛县| 绿春县| 永胜县| 溆浦县| 丰顺县| 湖口县| 乐陵市| 夏邑县| 普安县| 元谋县| 太白县| 玉树县| 巴里| 新宁县| 阳春市| 吴堡县| 任丘市| 嘉兴市| 乐安县| 赣榆县| 南华县| 克东县| 城步| 宁波市| 青铜峡市| 措美县|