delattr()從對象中刪除屬性(如果對象允許)。
delattr()的語法為:
delattr(object, name)
delattr()具有兩個參數(shù):
object-要從中刪除name屬性的對象
name-一個字符串,必須是要從object中刪除的屬性的名稱
delattr()不返回任何值(返回None)。它僅刪除屬性(如果對象允許)。
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ',point1.x) print('y = ',point1.y) print('z = ',point1.z) delattr(Coordinate, 'z') print('--刪除z屬性后--') print('x = ',point1.x) print('y = ',point1.y) # 引發(fā)錯誤 print('z = ',point1.z)
運行該程序時,輸出為:
x = 10 y = -5 z = 0 --刪除z屬性后-- x = 10 y = -5 Traceback (most recent call last): File "python", line 19, in <module> AttributeError: 'Coordinate' object has no attribute 'z'
在這里,使用delattr(Coordinate,'z')將屬性z從Coordinate類中刪除。
您還可以使用del運算符刪除對象的屬性。
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ',point1.x) print('y = ',point1.y) print('z = ',point1.z) # 刪除屬性z del Coordinate.z print('--刪除z屬性后--') print('x = ',point1.x) print('y = ',point1.y) # 引發(fā)屬性錯誤 print('z = ',point1.z)
該程序的輸出將與上面相同。