I'm doing an exercise in which you're supposed to calculate a score of how classy your items are. A tophat gives you 2 points, a bowtie gives you 4 points and a monocle gives you 5 points. I've initiated a dictionary with these items on each class instance, yet when I use getattr to check if the item has the attribute it always returns None.
class Classy(object):
def __init__(self):
self.items = []
self.classyItems = {'tophat': 2, 'bowtie': 4, 'monocle': 5}
def addItem(self, str):
self.items.append(str)
def getClassiness(self):
classiness = 0
for item in self.items:
itemIsClassy = getattr(self.classyItems, item, None) # Why does this always return none?
if itemIsClassy:
classiness += itemIsClassy
else:
pass
return classiness
# Test cases
me = Classy()
# Should be 0
print me.getClassiness()
me.addItem("tophat")
# Should be 2
print me.getClassiness() # I'm getting 0
Why is getattr returning None when self.classyItems clearly has the attribute of tophat?
Thanks for the help everyone! I was still confused after reading the answer and simply reading that dictionary keys are not attributes here helped me. Is Python dict an Object?
getattraccesses attributes and/or methods, butclassyItemsis a dict which doesn't have any (visible) attributes1 and stores its contents as key-value pairs2.In your case you should use
dict.getinstead ofgetattr, more specificallyself.classyItems.get(item, None), to access the values with default.1Dictionaries have methods that could be accessed using
getattrthough.2That's why you access them using
d[key]instead ofd.key.