Kodeclik Blog
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.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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 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.
class Book:
def __init__(self, name, year, author, publisher):
self.name = name
self.year = year
self.author = author
self.publisher = publisher
mybook = Book("The Adventures of Sherlock Holmes", 1891,
"Sir Arthur Conan Doyle", "Strand Publishing")
print(hasattr(mybook,'name'))
True
print(hasattr(mybook,'address'))
False
print(hasattr(mybook,name))
Traceback (most recent call last):
File "main.py", line 12, in <module>
print(hasattr(mybook,name))
NameError: name 'name' is not defined