Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python delattr() Function

Python delattr() Function

Python3 Built-in Functions Python3 built-in function


delattr() is a built-in Python function that deletes an object attribute.

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

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


Basic syntax and parameters

Syntax format

delattr(object, name)

Parameter Description

Function description


Example

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 an 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))

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

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

Result:

Multiple attributes can be deleted dynamically.

delattr() together with hasattr() is safer to use.


Python3 Built-in Functions Python3 built-in function