class MyClass: def __init__(self): self.attr1 = 1 self.attr2 = 2 obj = MyClass() # Check if the object has the attribute "attr1" if hasattr(obj, "attr1"): print("obj has attribute 'attr1'") else: print("obj does not have attribute 'attr1'") # Check if the object has the attribute "attr3" if hasattr(obj, "attr3"): print("obj has attribute 'attr3'") else: print("obj does not have attribute 'attr3'")
obj has attribute 'attr1' obj does not have attribute 'attr3'
To check if an object has an attribute in Python, you can use the hasattr function. The hasattr function returns a Boolean value indicating whether the object has the specified attribute. If the attribute exists, hasattr returns True, otherwise it returns False.
You can also use the getattr function to check if an object has an attribute. Here is an example of how to do this:
class MyClass: def __init__(self): self.attr1 = 1 self.attr2 = 2 obj = MyClass() # Check if the object has the attribute "attr1" try: getattr(obj, "attr1") print("obj has attribute 'attr1'") except AttributeError: print("obj does not have attribute 'attr1'") # Check if the object has the attribute "attr3" try: getattr(obj, "attr3") print("obj has attribute 'attr3'") except AttributeError: print("obj does not have attribute 'attr3'")
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.