Python 中的 delattr() 和 del()

pythonserver side programmingprogramming

这两个函数用于从类中删除属性。delattr() 允许动态删除属性,而 del() 在删除属性时效率更高。

使用 delattr()

语法:delattr(object_name, attribute_name)
其中 object name 是对象的名称,实例化类。
Attribute_name 是要删除的属性的名称。

示例

在下面的示例中,我们考虑一个名为 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()

语法:del(object_name.attribute_name)
其中 object name 是对象的名称,实例化类。
Attribute_name 是要删除的属性的名称。

示例

我们用 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'

相关文章