Python delattr() 函式



**Python delattr() 函式**用於從物件中刪除屬性。刪除指定的屬性後,如果嘗試使用類物件呼叫它,則會引發錯誤。

那些特定於類物件的屬性稱為例項屬性。類的兩個物件可能包含或可能不包含公共屬性。

**delattr()** 函式是內建函式之一,不需要匯入任何模組。

語法

Python **delattr()** 函式的語法如下所示:

delattr(object, attribute)

引數

Python **delattr()** 函式接受兩個引數:

  • **object** - 此引數表示要從中刪除屬性的物件。

  • **attribute** - 它指示要從指定物件中刪除的屬性。

返回值

Python **delattr()** 函式不返回值。

delattr() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **delattr()** 函式

示例:delattr() 函式的基本用法

以下示例顯示了 Python delattr() 函式的基本用法。在這裡,我們刪除指定類的屬性,並藉助 hasattr() 函式檢查屬性是否已成功刪除。

class NewClass:
   newAttr = "Simply Easy Learning"

print("Before deleting the attribute:")    
print("Is attribute exist:", hasattr(NewClass, 'newAttr')) 
delattr(NewClass, 'newAttr')
print("After deleting the attribute:")
print("Is attribute exist:", hasattr(NewClass, 'newAttr'))

執行上述程式時,會產生以下結果:

Before deleting the attribute:
Is attribute exist: True
After deleting the attribute:
Is attribute exist: False

示例:使用 delattr() 刪除類物件的屬性

delattr() 函式刪除類物件的屬性。在此示例中,我們刪除建構函式主體中存在的 newAttr 屬性。

class NewClass:
   def __init__(self):
      self.newAttr = "Simply Easy Learning"

newObj = NewClass()
print("Before deleting the attribute:") 
print("Is attribute exist:", hasattr(newObj, 'newAttr'))  
delattr(newObj, 'newAttr')
print("After deleting the attribute:") 
print("Is attribute exist:", hasattr(newObj, 'newAttr')) 

以下是上述程式碼的輸出:

Before deleting the attribute:
Is attribute exist: True
After deleting the attribute:
Is attribute exist: False

示例:刪除物件期間出錯

如果嘗試使用 delattr() 函式刪除不存在的屬性,則程式碼將丟擲 AttributeError,如下面的程式碼所示。

class NewClass:
   pass

newObj = NewClass()
try:
   delattr(newObj, 'newAttr')
except AttributeError as exp:
   print(exp)   

上述程式碼的輸出如下:

'NewClass' object has no attribute 'newAttr'

示例:使用 delattr() 從模組中刪除方法

delattr() 函式還允許我們從 Python 的現有模組中刪除方法。在下面的程式碼中,匯入了 math 模組。然後,藉助 delattr() 函式,我們刪除了 math 模組的sqrt() 方法

import math

print("Before deletion:", hasattr(math, 'sqrt'))  
delattr(math, 'sqrt')
print("After deletion:", hasattr(math, 'sqrt'))

以下是上述程式碼的輸出:

Before deletion: True
After deletion: False
python_built_in_functions.htm
廣告