Skip to content

delattr

请查看 Python 内建函数列表 了解更多相关 API。

说明:删除指定的属性。参考 hasattrgetattrsetattr 函数。

python
def delattr(obj, name:str):
    '''
    删除指定的属性

    :param obj: 一个对象
    :param name: 要删除的属性的名字
    '''

示例:

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)
print(p.name)

# 删除name属性
delattr(p, 'name')

try:
    print(p.name)
except AttributeError as e:
    print(f"错误: {e}")  # 输出: 错误: 'Person' object has no attribute 'name'