delattr Example
The delattr()
function removes an attribute from an object dynamically. It’s useful when you need to delete properties at runtime, especially in dynamic objects and class manipulation.
Simple Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
delattr(person, "age")
print(hasattr(person, "age")) # Output: False
Here, delattr(person, "age")
removes the age
attribute from the object.
Syntax
delattr(object, attribute_name)
- object → The instance of a class.
- attribute_name → The name of the attribute to delete (as a string).
This is the same as using:
del person.age
1. Deleting an Attribute Dynamically
delattr()
is useful when you don’t know the attribute name in advance.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car = Car("Tesla", "Model 3")
attr_to_delete = "model"
delattr(car, attr_to_delete)
print(hasattr(car, "model")) # Output: False
Perfect when working with dynamically created attributes.
2. Using delattr()
in a Class Method
You can define a method to remove attributes within a class.
class User:
def __init__(self, username, email):
self.username = username
self.email = email
def remove_email(self):
delattr(self, "email")
user = User("john_doe", "john@example.com")
user.remove_email()
print(hasattr(user, "email")) # Output: False
Useful for resetting or cleaning up object properties.
3. Handling Missing Attributes Safely
Trying to delete a non-existent attribute raises an error. Handle it using hasattr()
.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
product = Product("Laptop", 1200)
if hasattr(product, "price"):
delattr(product, "price")
This ensures you only delete attributes that exist.
Key Notes
- ✔ Deletes an attribute dynamically – useful for modifying objects at runtime.
- ✔ Equivalent to
del object.attribute
, but allows for dynamic attribute names. - ✔ Use
hasattr()
before deleting to avoid errors. - ✔ Useful for cleanup methods in classes where attributes might change.
By using delattr()
, you can modify objects dynamically, clean up attributes, and handle changing class structures efficiently. 🚀