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.
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.