Kodeclik Blog

Python hasattr()

Let us create a class in Python to represent books:
We can now create one specific book:
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:
The output is:
On the other hand, if we try:
The output will be:
Be careful to input the desired attribute in quotes. For instance, if you try:
You will get the error:
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 thePython __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.

Join our mailing list

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

Copyright @ Kodeclik 2024. All rights reserved.