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


Python delattr()用法及代碼示例

Python delattr() 函數用於從類中刪除屬性。它有兩個參數,第一個是我們要刪除的類對象,第二個是我們要刪除的屬性的名稱。

用法

delattr (object, name)  

參數

Parameter



Description

object

An object from which we want to delete the attribute

name

The name of the attribute we want to delete

delattr() 方法返回一個複數。

範例1:

使用屬性名稱、持續時間、價格、評級創建課程。創建了一個類的實例,現在我們使用 delattr() 方法刪除 rating 屬性。最後,我們檢查 rating 屬性是否存在。一個 try 塊用於處理 keyError

Python3


class course:
    name = "data structures using c++"
    duration_months = 6
    price = 20000
    rating = 5
# creating an object of course
print(course.rating)
# deleting the rating attribute from object
delattr(course, 'rating')
# checking if the rating attribute is there or not
try:
    print(course.rating)
except Exception as e:
    print(e)
輸出
5
type object 'course' has no attribute 'rating'

範例2:

使用屬性名稱、持續時間、價格、評級創建課程。創建了一個類的實例,現在我們使用 delattr() 方法刪除價格屬性。最後,我們檢查價格屬性是否存在。一個 try 塊用於處理 keyError

Python3


class course:
    name = "data structures using c++"
    duration_months = 6
    price = 20000
    rating = 5
# creating an object of course
print(course.price)
# deleting the price attribute from object
delattr(course, 'price')
# checking if the price attribute is there or not
try:
    print(course.price)
except Exception as e:
    print(e)
輸出
20000
type object 'course' has no attribute 'price'



相關用法


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