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() and del()用法及代碼示例
- Python Tkinter destroy()用法及代碼示例
- Python degrees() and radians()用法及代碼示例
- Python dict()用法及代碼示例
- Python datetime astimezone()用法及代碼示例
- Python datetime timetuple()用法及代碼示例
- Python datetime timetz()用法及代碼示例
- Python dictionary values()用法及代碼示例
- Python datetime isocalendar()用法及代碼示例
- Python date toordinal()用法及代碼示例
- Python dir()用法及代碼示例
- Python date replace()用法及代碼示例
- Python date strftime()用法及代碼示例
- Python datetime date()用法及代碼示例
- Python datetime isoformat()用法及代碼示例
- Python divmod()用法及代碼示例
- Python datetime __str__()用法及代碼示例
- Python date weekday()用法及代碼示例
- Python date isoweekday()用法及代碼示例
- Python datetime.timedelta()用法及代碼示例
注:本文由純淨天空篩選整理自 Python delattr() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。