當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python __new__用法及代碼示例

Python是一種麵向對象的編程語言,即Python中的所有對象都是對象。 Python中有一種特殊的方法,稱為魔術方法或dunder方法(這裏的dunder表示“Double Underscores”)。 Python中的Dunder或magic方法是方法名稱中帶有兩個前綴和後綴下劃線的方法。這些通常用於操作員重載。魔術方法的幾個示例是:__init____add____len____repr__ 等等

注意:要了解有關魔術方法的更多信息,請單擊此處。

__new__方法


每當實例化一個類__new__ __init__ 方法被調用。__new__ 創建對象時將調用方法,並且__init__ 方法將被調用以初始化對象。在基層object,__new__方法定義為靜態方法,需要傳遞參數clscls 表示需要實例化的類,並且編譯器在實例化時自動提供此參數。

用法:



class class_name:
    def __new__(cls, *args, **kwargs):
        statements
        .
        .
        return super(class_name, cls).__new__(cls, *args, **kwargs)

注意:實例可以在裏麵創建__new__ 通過使用super 函數或直接調用__new__ 對象的方法,如果父類是對象的話。那是instance = super(MyClass, cls).__new__(cls, *args, **kwargs)或者instance = object.__new__(cls, *args, **kwargs)

如果類中同時存在__init__方法和__new__方法,則將首先執行__new__方法並決定是否使用__init__方法,因為其他類的構造函數可以由__new__方法調用,或者可以簡單地返回其他對象作為的實例。這個班。

例:

# Python program to  
# demonstrate __new__ 
  
# don't forget the object specified as base 
class A(object):
    def __new__(cls):
         print("Creating instance") 
         return super(A, cls).__new__(cls) 
  
    def __init__(self):
        print("Init is called") 
  
A()

輸出:

Creating instance
Init is called

上麵的示例顯示,調用類名時會自動調用__new__方法,而每次__new__方法返回該類的實例時,都會調用__init__方法,並將返回的實例作為__init__傳遞給__init__。self參數,因此,即使您要將該實例全局/靜態保存到某個位置,並且每次從__new__返回它,那麽每次這樣做都會調用__init__。

這意味著,如果__new__方法省略了super,則__init__方法將不會執行。讓我們看看是否是這種情況。

# Python program to 
# demonstrate __new__ 
  
class A(object):
    def __new__(cls):
        print("Creating instance") 
  
    # It is not called 
    def __init__(self):
        print("Init is called") 
  
print(A())

輸出:

Creating instance
None

在上麵的示例中,可以看出未調用__init__方法,並且實例化為None 因為構造函數沒有返回任何東西。讓我們看看如果__new__和__init__方法都返回了什麽會發生什麽。

# Python program to 
# demonstrate __new__ 
  
class A(object):
    # new method returning a string 
    def __new__(cls):
        print("Creating instance") 
        return "GeeksforGeeks"
  
class B(object):
    # init method returning a string 
    def __init__(self):
        print("Initializing instance") 
        return "GeeksforGeeks"
  
print(A()) 
print(B())

輸出:

Creating instance
GeeksforGeeks
Initializing instance
Traceback (most recent call last):
  File "/home/62216eb30d3856048eff916fb8d4c32d.py", line 17, in 
    print(B())
TypeError:__init__() should return None, not 'str'

調用__init__方法的處理程序會引發此TypeError,從__init__方法返回任何內容都沒有任何意義,因為它的目的隻是改變新創建實例的新鮮狀態。

讓我們嘗試一個示例,其中__new__方法返回另一個類的實例。
例:

# Python program to 
# demonstrate __new__ method 
  
# class whose object 
# is returned 
class GeeksforGeeks(object):
    def __str__(self):
        return "GeeksforGeeks"
          
# class returning object 
# of different class 
class Geek(object):
    def __new__(cls):
        return GeeksforGeeks() 
          
    def __init__(self):
        print("Inside init") 
          
print(Geek())

輸出:

GeeksforGeeks




相關用法


注:本文由純淨天空篩選整理自nikhilaggarwal3大神的英文原創作品 __new__ in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。