all Python 3Built-in functionsterm
delattr
OOP
Deletes the named attribute of an object. Equivalent to del obj.attr, but lets you pass the attribute name dynamically as a string.
Syntax
delattr(object, name)
delattr earns its keep only when the attribute name is computed at run time; if you know the name in advance, write del obj.attr. It removes an instance attribute: if x lives in the class body rather than being assigned through self, delattr(instance, 'x') raises AttributeError even though reading obj.x worked fine. A missing attribute raises AttributeError too, so guard the call with hasattr or try/except.
Examples
class A:
x = 1
def __init__(self): self.y = 2
a = A()
delattr(a,'y')
print(hasattr(a,'y')) # → False
delattr(A,'x')
print(hasattr(A,'x')) # → False
try:
delattr(a,'z')
except AttributeError as e: print(e)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy