delattr()
的语法是
delattr(object, name)
delattr() 参数
delattr()
接受两个参数
- object - 要从中删除 name 属性的对象
- name - 一个字符串,必须是要从 object 中删除的属性的名称
delattr() 的返回值
delattr()
不返回任何值(返回 None
)。它只删除一个属性(如果对象允许的话)。
示例 1:delattr() 如何工作?
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 <module> AttributeError: 'Coordinate' object has no attribute 'z'
这里,使用 delattr(Coordinate, 'z')
从 Coordinate 类中删除了属性 z。
示例 2:使用 del 运算符删除属性
您也可以使用 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)
程序的输出将与上面相同。
另请阅读