📅  最后修改于: 2020-09-20 03:56:48             🧑  作者: Mango
delattr()
的语法为:
delattr(object, name)
delattr()
具有两个参数:
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('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# Raises Error
print('z = ',point1.z)
输出
x = 10
y = -5
z = 0
--After deleting z attribute--
x = 10
y = -5
Traceback (most recent call last):
File "python", line 19, in
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)
# Deleting attribute z
del Coordinate.z
print('--After deleting z attribute--')
print('x = ',point1.x)
print('y = ',point1.y)
# Raises Attribute Error
print('z = ',point1.z)
该程序的输出将与上面相同。