当前位置: 首页>>代码示例>>用法及示例精选>>正文


Python delattr() and del()用法及代码示例

德莱特

delattr()方法用于在对象的事先许可下从对象中删除命名属性。句法:

delattr(object, name)

The function takes only two parameter:

object: from which 
the name attribute is to be removed.
name: of the attribute 
which is to be removed.

The function doesn't returns any value, 
it just removes the attribute, 
only if the object allows it.

工作方式:假设我们有一个名为Geek的类,它有5个学生作为属性。因此,使用delattr()方法,我们可以删除任何一个属性。

Python3


# Python code to illustrate delattr()
class Geek:
  stu1 = "Henry"
  stu2 = "Zack"
  stu3 = "Stephen"
  stu4 = "Amy"
  stu5 = "Shawn"
 
names = Geek()
 
print('Students before delattr()--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
print('Fifth = ',names.stu5)
 
# implementing the method
delattr(Geek, 'stu5')
 
print('After deleting fifth student--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
# this statement raises an error
print('Fifth = ',names.stu5)

输出:

Students before delattr()--
First =  Henry
Second =  Zack
Third =  Stephen
Fourth =  Amy
Fifth =  Shawn
After deleting fifth student--
First =  Henry
Second =  Zack
Third =  Stephen
Fourth =  Amy

当执行移至程序的最后一行时,即,调用第五个属性时,编译器将引发错误:



Traceback (most recent call last):
  File "/home/028e8526d603bccb30e9aeb7ece9e1eb.py", line 25, in 
    print('Fifth = ',names.stu5)
AttributeError:'Geek' object has no attribute 'stu5'

del运算符

Python中还有另一个运算符,其作用与delattr()方法类似。它是del运算符。让我们看看它是如何工作的。

Python3


# Python code to illustrate del()
class Geek:
  stu1 = "Henry"
  stu2 = "Zack"
  stu3 = "Stephen"
  stu4 = "Amy"
  stu5 = "Shawn"
 
names = Geek()
 
print('Students before del--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
print('Fifth = ',names.stu5)
 
# implementing the operator
del Geek.stu5
 
print('After deleting fifth student--')
print('First = ',names.stu1)
print('Second = ',names.stu2)
print('Third = ',names.stu3)
print('Fourth = ',names.stu4)
# this statement raises an error
print('Fifth = ',names.stu5)

输出:

Students before del--
First =  Henry
Second =  Zack
Third =  Stephen
Fourth =  Amy
Fifth =  Shawn
After deleting fifth student--
First =  Henry
Second =  Zack
Third =  Stephen
Fourth =  Amy

结果是一样的,但有一个错误:

Traceback (most recent call last):
  File "/home/7c239eef9b897e964108c701f1f94c8a.py", line 26, in 
    print('Fifth = ',names.stu5)
AttributeError:'Geek' object has no attribute 'stu5'

德尔VS delattr()

  1. 动态删除:del是更明确和有效的,并且delattr()允许动态属性删除。
  2. Speed:如果考虑并运行以上程序,则执行速度之间会有细微差别。与delattr()相比,del稍快一些,具体取决于机器。
  3. 字节码说明:与delattr()相比,del还占用更少的字节码指令。

因此,我们通过说del比delattr快一点来结束比较,但是当涉及到属性的动态删除时,delattr()具有优势,因为del运算符无法实现。

注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 delattr() and del() in Python。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。