Python delattr() 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
- 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 delete.
Function description
- Return Value: No return value.
- exception: if the attribute does not exist, an AttributeError is raised.
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
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:
- 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}
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 function