Hasattr() and Strings

I was taking the quiz in the Classes module of the Python course when I ran into this question:

What does the hasattr() function call in the last line here evaluate to?
class HoldsFive:
five = 5

five_holder = HoldsFive()

hasattr(five_holder, ‘five’)

The correct answer is that it evaluates to True. However, I’m confused as to why "five is in quotes in hasattr() even though “five” in HoldsFive doesn’t. Does this mean that the variable is automatically interpreted as a string and I have to specify it when I reference it as an argument to a function?

Hi @theq614,

See hasattr(object, name ).

When calling the hasattr function, we need to communicate to it the name of the attribute for which we are checking. That name needs to be provided as an expression that evaluates to a string. If we do not place quotes around a name that we supply as an argument, that name will be interpreted as a variable. If a variable by that name does not exist, Python will raise a NameError.

1 Like

Thank you! I really should reference the documentation more often.

1 Like