Python delattr()
Python delattr(object, name) deletes the named argument with the given name
from the object
.
In this tutorial, we will learn about the syntax of Python delattr() function, and learn how to use this function with the help of examples.
Syntax
The syntax of delattr() function is
delattr(object, name)
where
Parameter | Required/Optional | Description |
---|---|---|
object | Required | A Python object. |
name | Required | A string. |
Note: The function removes the attribute if and only if the object allows this operation.
Returns
The function returns None.
Example
In this example, we will define a class X with three attributes a, b and c. First we shall print the attributes for X, then delete the attribute c, and print the attributes of X.
We will use dir() builtin function to print the attributes of X.
Python Program
class X:
a = 1
b = 2
c = 3
print('Attributes in X before deleting c attribute')
for attr in dir(X):
if '__' not in attr:
print(attr)
delattr(X, 'c')
print('Attributes in X after deleting c attribute')
for attr in dir(X):
if '__' not in attr:
print(attr)
Output
Attributes in X before deleting c attribute
a
b
c
Attributes in X after deleting c attribute
a
b
Conclusion
In this Python Tutorial, we have learnt the syntax of Python delattr() builtin function, and also learned how to use this function, with the help of Python example programs.