Python delattr() 函数用于从对象中删除属性。一旦指定的属性被删除,如果我们尝试使用 class object 调用它,它将引发错误。
特定于类对象的那些属性称为 实例属性。一个类的两个对象可能包含也可能不包含公共属性。
delattr() 函数是内置函数之一,不需要导入任何模块。
语法
Python delattr() 函数的语法如下所示 -
delattr(object, attribute)
参数
Python delattr() 函数接受两个参数 -
- object − 此参数表示要从中删除属性的对象。
- attribute − 它指示要从指定对象中删除的属性。
返回值
Python delattr() 函数不返回任何值。
delattr() 函数示例
练习以下示例以了解 Python 中 delattr() 函数的用法:
示例:delattr() 函数的基本用法
以下示例显示了 Python delattr() 函数的基本用法。在这里,我们正在删除指定类的属性,并在 hasattr() 函数的帮助下,我们检查该属性是否已成功删除。
class NewClass:
newAttr = "Simply Easy Learning"
print("Before deleting the attribute:")
print("Is attribute exist:", hasattr(NewClass, 'newAttr'))
delattr(NewClass, 'newAttr')
print("After deleting the attribute:")
print("Is attribute exist:", hasattr(NewClass, 'newAttr'))
当我们运行上述程序时,它会产生以下结果——
Before deleting the attribute:
Is attribute exist: True
After deleting the attribute:
Is attribute exist: False
Is attribute exist: True
After deleting the attribute:
Is attribute exist: False
示例:使用 delattr() 删除类对象的属性
delattr() 函数删除类对象的属性。在此示例中,我们将删除存在于构造函数主体中的 newAttr 属性。
class NewClass:
def __init__(self):
self.newAttr = "Simply Easy Learning"
newObj = NewClass()
print("Before deleting the attribute:")
print("Is attribute exist:", hasattr(newObj, 'newAttr'))
delattr(newObj, 'newAttr')
print("After deleting the attribute:")
print("Is attribute exist:", hasattr(newObj, 'newAttr'))
以下是上述代码的输出 -
Before deleting the attribute:
Is attribute exist: True
After deleting the attribute:
Is attribute exist: False
Is attribute exist: True
After deleting the attribute:
Is attribute exist: False
示例:删除对象时出错
如果我们尝试使用 delattr() 函数删除不存在的属性,代码将抛出 AttributeError,如下面的代码所示。
class NewClass:
pass
newObj = NewClass()
try:
delattr(newObj, 'newAttr')
except AttributeError as exp:
print(exp)
上述代码的输出如下 -
'NewClass' object has no attribute 'newAttr'
示例:使用 delattr() 从模块中删除方法
delattr() 函数还允许我们从现有的 Python 模块中删除一个方法。在下面的代码中,导入了 math 模块。然后,在 delattr() 函数的帮助下,我们删除了 math 模块的 sqrt() 方法。
import math
print("Before deletion:", hasattr(math, 'sqrt'))
delattr(math, 'sqrt')
print("After deletion:", hasattr(math, 'sqrt'))
以下是上述代码的输出 -
Before deletion: True
After deletion: False
After deletion: False