Python 中的 delattr() 和 del()
这两个函数用于从类中删除属性。delattr() 允许动态删除属性,而 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'
广告