Python attribute check in OOP

Share Your Love

In Python attribute check, you can check if an attribute is present in an object using the hasattr() function or by using the in operator. Here’s how you can use each method:

  1. Using hasattr() function:
    The hasattr() function takes two arguments: the object you want to check and the name of the attribute you want to check for. It returns True if the attribute is present in the object, and False otherwise.
class MyClass:
    def __init__(self):
        self.attribute = 10

obj = MyClass()

# Check if 'attribute' is present in obj using hasattr()
if hasattr(obj, 'attribute'):
    print("Attribute 'attribute' is present.")
else:
    print("Attribute 'attribute' is not present.")

# Check if 'other_attribute' is present in obj using hasattr()
if hasattr(obj, 'other_attribute'):
    print("Attribute 'other_attribute' is present.")
else:
    print("Attribute 'other_attribute' is not present.")

Output:

Attribute 'attribute' is present.
Attribute 'other_attribute' is not present.
  1. Using in operator:
    You can also use the in operator to check if an attribute is present in an object. The in operator checks if a given attribute name exists as a key in the object’s attribute dictionary.
class MyClass:
    def __init__(self):
        self.attribute = 10

obj = MyClass()

# Check if 'attribute' is present in obj using the 'in' operator
if 'attribute' in obj.__dict__:
    print("Attribute 'attribute' is present.")
else:
    print("Attribute 'attribute' is not present.")

# Check if 'other_attribute' is present in obj using the 'in' operator
if 'other_attribute' in obj.__dict__:
    print("Attribute 'other_attribute' is present.")
else:
    print("Attribute 'other_attribute' is not present.")

Output:

Attribute 'attribute' is present.
Attribute 'other_attribute' is not present.

Both hasattr() and the in operator can be used to check if an attribute is present in an object. Choose the method that suits your needs and coding style.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter