hasattr(): determine whether an object has a specific attribute

hasattr(object, name) Returns Boolean ( True or False ) after checking attribute of the input object
object Object for which the attribute is to be checked .
name name of the the attribute .
Read more on Class Object and Attributes
Output of hasattr() is True or False.
class Animal():

     #class attributes
    species='carnivores'

     #instance attributes
    def __init__(self1,name1,age):
        self1.name= name1
        self1.age=age
        

 #instantiate the Animal  class
tiger=Animal("Ronald",5) 
print(hasattr(tiger,'age'))    # True 
print(hasattr(tiger,'height')) # False 
In above code we got True for the attribute age , but got False for attribute height as it is not declared.

Benefits of Using hasattr()

  • Safe Attribute Access: It allows for safe attribute access by checking for an attribute's existence before accessing it, thus avoiding potential AttributeErrors.
  • Dynamic Code: Useful in scenarios where we need to work with objects dynamically, and we might not know if an object has a specific attribute.
  • Conditional Logic: Enables writing conditional logic based on the presence or absence of attributes in objects, making our code more flexible and robust.

In summary, hasattr() is a handy function in Python for checking the existence of an attribute in an object, providing a way to write safer and more adaptable code.
All Built in Functions in Python setattr() delattr() getattr()

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer