德萊特
delattr()方法用於在對象的事先許可下從對象中刪除命名屬性。句法:
delattr(object, name) The function takes only two parameter: object: from which the name attribute is to be removed. name: of the attribute which is to be removed. The function doesn't returns any value, it just removes the attribute, only if the object allows it.
工作方式:假設我們有一個名為Geek的類,它有5個學生作為屬性。因此,使用delattr()方法,我們可以刪除任何一個屬性。
Python3
# Python code to illustrate delattr()
class Geek:
stu1 = "Henry"
stu2 = "Zack"
stu3 = "Stephen"
stu4 = "Amy"
stu5 = "Shawn"
names = Geek()
print('Students before delattr()--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
print('Fifth = ',names.stu5)
# implementing the method
delattr(Geek, 'stu5')
print('After deleting fifth student--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
# this statement raises an error
print('Fifth = ',names.stu5)
輸出:
Students before delattr()-- First = Henry Second = Zack Third = Stephen Fourth = Amy Fifth = Shawn After deleting fifth student-- First = Henry Second = Zack Third = Stephen Fourth = Amy
當執行移至程序的最後一行時,即,調用第五個屬性時,編譯器將引發錯誤:
Traceback (most recent call last): File "/home/028e8526d603bccb30e9aeb7ece9e1eb.py", line 25, in print('Fifth = ',names.stu5) AttributeError:'Geek' object has no attribute 'stu5'
del運算符
Python中還有另一個運算符,其作用與delattr()方法類似。它是del運算符。讓我們看看它是如何工作的。
Python3
# Python code to illustrate del()
class Geek:
stu1 = "Henry"
stu2 = "Zack"
stu3 = "Stephen"
stu4 = "Amy"
stu5 = "Shawn"
names = Geek()
print('Students before del--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
print('Fifth = ',names.stu5)
# implementing the operator
del Geek.stu5
print('After deleting fifth student--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
# this statement raises an error
print('Fifth = ',names.stu5)
輸出:
Students before del-- First = Henry Second = Zack Third = Stephen Fourth = Amy Fifth = Shawn After deleting fifth student-- First = Henry Second = Zack Third = Stephen Fourth = Amy
結果是一樣的,但有一個錯誤:
Traceback (most recent call last): File "/home/7c239eef9b897e964108c701f1f94c8a.py", line 26, in print('Fifth = ',names.stu5) AttributeError:'Geek' object has no attribute 'stu5'
德爾VS delattr()
- 動態刪除:del是更明確和有效的,並且delattr()允許動態屬性刪除。
- Speed:如果考慮並運行以上程序,則執行速度之間會有細微差別。與delattr()相比,del稍快一些,具體取決於機器。
- 字節碼說明:與delattr()相比,del還占用更少的字節碼指令。
因此,我們通過說del比delattr快一點來結束比較,但是當涉及到屬性的動態刪除時,delattr()具有優勢,因為del運算符無法實現。
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 delattr() and del() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。