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


Python delattr()用法及代碼示例

Python delattr() 函數用於從類中刪除屬性。它需要兩個參數,第一個是類的對象,第二個是我們要刪除的屬性。刪除該屬性後,它在類中不再可用,如果嘗試使用類對象調用它,則會引發錯誤。

簽名

delattr (object, name)

參數

object:包含屬性的類的對象。

name:要刪除的屬性的名稱。它必須是一個字符串。

返回

它返回一個複數。

讓我們看一些 delattr() 函數的例子來理解它的函數。

Python delattr() 函數示例 1

這是一個簡單的例子,包含一個 Student 類,通過使用 delattr() 函數,我們將刪除它的 email 屬性。

# Python delattr() function example
class Student:
    id = 101
    name = "Rohan"
    email = "rohan@abc.com"
    def getinfo(self):
        print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'email') # Removing attribute
s.getinfo() # error:no attribute 'email' is available

輸出:

AttributeError:'Student' object has no attribute 'email'
101 Rohan [email protected]

Python delattr() 函數示例2

如果我們刪除一個不存在的屬性,它會拋出一個錯誤。

# Python delattr() function example
class Student:
    id = 101
    name = "Rohan"
    email = "rohan@abc.com"
# Declaring function
    def getinfo(self):
        print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error:throws an error

輸出:

AttributeError:course






相關用法


注:本文由純淨天空篩選整理自 Python delattr() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。