Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

Python hasattr()

Let us create a class in Python to represent books:

class Book:
 def __init__(self, name, year, author, publisher):
  self.name = name
  self.year = year
  self.author = author
  self.publisher = publisher

We can now create one specific book:

mybook = Book("The Adventures of Sherlock Holmes", 1891, 
              "Sir Arthur Conan Doyle", "Strand Publishing")

Python hasattr()

The Python hasattr() function takes an object as input and returns True if the object has the specified attribute and false otherwise. If we try:

print(hasattr(mybook,'name'))

The output is:

True

On the other hand, if we try:

print(hasattr(mybook,'address'))

The output will be:

False

Be careful to input the desired attribute in quotes. For instance, if you try:

print(hasattr(mybook,name))

You will get the error:

Traceback (most recent call last):
File "main.py", line 12, in <module>
  print(hasattr(mybook,name))
NameError: name 'name' is not defined

When should we use hasattr()? hasattr() is a very useful function to check for the existence of an attribute before attempting to access it. If hasattr() returns False, you will know that the desired attribute does not exist and thus you can develop alternate program logic.

If you liked learning about hasattr(), you will also like our blogposts on Python's not in operator and the
Python __call__ method.

Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.