📅  最后修改于: 2023-12-03 15:18:54.771000             🧑  作者: Mango
delattr()
The delattr()
function in Python is used to delete an attribute from an object. It takes two parameters - the object and the name of the attribute to be deleted.
The syntax of delattr()
function is:
delattr(object, attribute)
The delattr()
function doesn't return any value. It deletes the specified attribute and raises an AttributeError
if the attribute does not exist.
Let's see an example to understand how delattr()
works:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("John", 25)
# Print the age attribute
print(student1.age) # Output: 25
# Delete the age attribute
delattr(student1, "age")
# Try to access the deleted attribute
print(student1.age) # Raises AttributeError: 'Student' object has no attribute 'age'
In the above example, we have a Student
class with name
and age
attributes. We create an instance of the Student
class and print the age
attribute value. Then, we use the delattr()
function to delete the age
attribute. Finally, when we try to access the age
attribute again, it raises an AttributeError
as the attribute doesn't exist anymore.
The delattr()
function is a useful tool in Python to delete attributes from an object. It allows you to dynamically manage the attributes of an object during runtime.