Python中的delattr()和del()

这两个函数用于从类中删除属性。在delattr()允许属性的dynamoc缺失,而del()在删除属性更高效的明确。

使用 delattr()

Syntax: delattr(object_name, attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

示例

在下面的示例中,我们考虑一个名为custclass的类。它具有客户的ID作为其属性。接下来,我们将该类实例化为一个名为customer的对象,并打印其属性。

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
print(customer.custid3)

输出结果

运行上面的代码给我们以下结果-

0
1
2

示例

在下一步中,我们通过应用delattr()方法再次运行程序。这次,当我们要打印id3时,由于该属性已从类中删除,因此会出现错误。

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
delattr(custclass,'custid3')
print(customer.custid3)

输出结果

运行上面的代码给我们以下结果-

0
Traceback (most recent call last):
1
File "xxx.py", line 13, in print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'

使用 del()

Syntax: del(object_name.attribute_name)
Where object name is the name of the object, instantiated form the class.
Attribute_name is the name of the attribute to be deleted.

示例

我们用del()函数重复上面的例子。请注意,语法与delattr()

class custclass:
   custid1 = 0
   custid2 = 1
   custid3 = 2
customer=custclass()
print(customer.custid1)
print(customer.custid2)
del(custclass.custid3)
print(customer.custid3)

输出结果

运行上面的代码给我们以下结果-

0
1
Traceback (most recent call last):
File "xxx.py", line 13, in
print(customer.custid3)
AttributeError: 'custclass' object has no attribute 'custid3'