很喜歡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.
新聞熱點
疑難解答