Python delattr() Function

Python3 内置函数Python3 Built-in Functions


delattr()is a built-in function in Python used to delete object attributes.

delattr()It can delete the specified attribute of an object. Similar todelthe del statement, but allows dynamically specifying the attribute to be deleted via a string.

Word Definitions: delattr 是 delete attribute(删除属性)的缩写。


Basic Syntax and Parameters

Syntax Format

delattr(object, name)

Parameter Description

  • Parameter object:
    • Type: Any object
    • Description: The object whose attribute is to be deleted.
  • Parameter name:
    • Type: String
    • Description: The name of the attribute to be deleted.

Function Description

  • Return Value: No return value.
  • Exception: If the attribute does not exist, an AttributeError will be raised.

Examples

Example 1: Basic Usage

Example

class Person:
    def __init__(self):
        self.name = "Tom"
        self.age = 20
        self.city = "Beijing"

p = Person()
print(vars(p))
# Output: {'name': 'Tom', 'age': 20, 'city': 'Beijing'}

# Delete the attribute
delattr(p, "age")
print(vars(p))
# Output: {'name': 'Tom', 'city': 'Beijing'}

# Equivalent to del p.age

Expected output:

{'name': 'Tom', 'age': 20, 'city': 'Beijing'}
{'name': 'Tom', 'city': 'Beijing'}

Code analysis:

  1. delattr(p, "age") is equivalent to del p.age.

Example 2: Dynamic Deletion

Example

class Data:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

d = Data()
print(vars(d))

# Dynamically delete attributes
attrs_to_delete = ["a", "c"]
for attr in attrs_to_delete:
    if hasattr(d, attr):
        delattr(d, attr)

print(vars(d))  # Output: {'b': 2}

Output:

Multiple attributes can be deleted dynamically.

delattr()Together withhasattr()it is safer to use.


Python3 内置函数Python3 Built-in Functions


Other Extensions