delattr(): Delete Attribute Function
delattr | |
---|---|
Language | Python |
Category | Function |
Part Of | Built In Functions |
Named Arguments Count | 0 |
Unnamed Arguments Count | 2 |
Official Documentation | delattr Function |
1 Description
The Python delattr
function is used to delete an attribute in an object. The delattr
function accepts two arguments. The first argument is the object which has an attribute which you
would like to delete, the second argument is the name of the attribute you would like to delete as
a string.
2 Prototype
Below is the function prototype for the delattr
function.
delattr(object, name)
3 Arguments
delattr Function Arguments | ||||
---|---|---|---|---|
Name | Type | Default Value | Category | Description |
object |
object |
Unnamed argument(s) | The object that has the attribute you would like to delete. | |
name |
string |
|
Unnamed argument(s) | The name of the attribute you would like to delete from the object. |
4 Returns
delattr Function Returns | |
---|---|
Return Type | Explanation |
None |
The delattr function will always return None. |
5 Raises
delattr Function Raises | |
---|---|
Exception Type | Raised When |
AttributeError |
An attempt is made to delete an attribute that does not exist. |
TypeError |
The second argument provided is not a string type. |
6 Examples
6.1 Delete an Attribute
#!/usr/bin/python3
class Fruit:
def __init__(self, name):
self.name = name
def main():
# Create object, with a name 'orange'
fruit_1 = Fruit("orange")
# print the name of the fruit
print("fruit_1.name =", fruit_1.name)
# now delete the attribute 'name' from object 'fruit_1'
delattr(fruit_1, "name")
# now try to access the object attribute 'name'
try:
print("fruit_1.name =", fruit_1.name)
except AttributeError as exception:
# exception is triggered because the attribute 'name' is gone
print("object 'fruit_1' has no attribute 'name'.")
if __name__ == "__main__":
main()
user-1@vm:~/Documents$ ./delattr_example_1.py
fruit_1.name = orange
object 'fruit_1' has no attribute 'name'.
user-1@vm:~/Documents$
This document was last updated: