跳到主要内容

Python delattr() 函数

delattr() 的语法是:

delattr(object, name)

delattr() 参数

delattr() 接受两个参数:

  • object - 要从中移除 name 属性的对象
  • name - 必须是要从对象中移除的属性的名称的字符串

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('--删除 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' 对象没有属性 '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)

# 删除属性 z
del Coordinate.z

print('--删除 z 属性后--')
print('x = ', point1.x)
print('y = ', point1.y)

# 引发属性错误
print('z = ', point1.z)

程序的输出将与上面相同。