Python 中的 delattr() 和 del()


這兩個函式用於從類中刪除屬性。delattr() 允許動態刪除屬性,而 del() 則在刪除屬性時更具明確的高效性。

使用 delattr()

Syntax: delattr(object_name, attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

示例

在下例中,我們考慮一個名為 custclass 的類。它擁有客戶的 ID 作為其屬性。接下來,我們將該類例項化為一個名為 customer 的物件,並列印其屬性。

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
print(customer.custid3)

輸出

執行以上程式碼會產生以下結果:

0
1
2

示例

在下一步中,我們再次透過應用 delattr() 函式來執行程式。這一次,當我們想要列印 id3 時,會收到一個錯誤,因為該屬性已從類中刪除。

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
delattr(custclass,'custid3')
print(customer.custid3)

輸出

執行以上程式碼會產生以下結果:

0
Traceback (most recent call last):
1
File "xxx.py", line 13, in print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'

使用 del()

Syntax: del(object_name.attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

示例

我們用 del() 函式來重複上面的示例。請注意,它的語法與 delattr() 不同

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
del(custclass.custid3)
print(customer.custid3)

輸出

執行以上程式碼會產生以下結果:

0
1
Traceback (most recent call last):
File "xxx.py", line 13, in
print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'

更新於:07-08-2019

421 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

入門
廣告
© . All rights reserved.