📜  Python delattr()

📅  最后修改于: 2020-09-20 03:56:48             🧑  作者: Mango

delattr()从对象中删除属性(如果对象允许)。

delattr()的语法为:

delattr(object, name)

delattr()参数

delattr()具有两个参数:

  1. object-要从中删除name属性的对象
  2. 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 
AttributeError: 'Coordinate' object has no attribute 'z'

在这里,使用delattr(Coordinate, 'z')将属性zCoordinate类中删除。

示例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)

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