Python delattr() 函數

Python 內置函數 Python 內置函數


描述

delattr 函數用於刪除屬性。

delattr(x, 'foobar') 相等於 del x.foobar

語法

delattr 語法:

delattr(object, name)

參數

  • object -- 對象。
  • name -- 必須是對象的屬性。

返回值

無。

實例

以下實例展示了 delattr 的使用方法:

#!/usr/bin/python # -*- coding: UTF-8 -*- 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) # 觸發錯誤 print('z = ',point1.z)

輸出結果:

('x = ', 10)
('y = ', -5)
('z = ', 0)
--刪除 z 屬性後--
('x = ', 10)
('y = ', -5)
Traceback (most recent call last):
  File "test.py", line 22, in <module>
    print('z = ',point1.z)
AttributeError: Coordinate instance has no attribute 'z'

Python 內置函數 Python 內置函數