Hasattr. There are two built-in functions other than getattr and setattr. With hasattr we see if an attribute (field) exists on the class instance. It returns True or False.
Delattr With delattr we remove an attribute from the class. This is another syntax form for the del operator.
Tip We use the del operator to remove things (as from a dictionary). This is a special syntax form.
Python program that uses hasattr, delattr
box = Box()
# Create a width attribute.
setattr(box, "width", 15)
# The attribute exists.
if hasattr(box, "width"):
# Delete the width attribute.delattr(box, "width")
# Width no longer exists.
if not hasattr(box, "width"):
By understanding type, setattr and getattr, we learn more about how Python classes work. This knowledge helps us write better programs.
Statements in Python, like "class" declarations, can be directly translated to built-in method calls like "type." Low-level parts of the language are used to implement high-level parts.