delattr()从对象中删除属性(如果对象允许)。
delattr()的语法为:
delattr(object, name)
delattr()具有两个参数:
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) # 引发错误 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) # 引发属性错误 print('z = ',point1.z)
该程序的输出将与上面相同。