Ex 43 my 'ah-ha' moment - the dictionary in Map()

This exercise had me stumped for a week. I thought I understood the Engine() and Map() classes, but I now see that my initial understanding was off.

To me it seemed the classes names were just being referenced in the dictionary as I was thinking back to a previous mention somewhere about being able to access class functions directly without creating an instance of the class, and I assumed this was happening.

It didn’t fit expectation of something like roomA_instance = RoomA()

Based on my wrongful thinking, I built a dumbed-down version of Map() without help, but my version used if, elif, else statements in Map() to simply return the class names direct.

    def get_place(self, place_name):
    if place_name = 'starting_place':
        return StartingPlace()
    elif place_name = 'middle_place':
        return MiddlePlace()
    elif place_name = 'finish_place':
        return FinishPlace()
    else:
        return DeathPlace()

It worked but I could never escape the while loop in Engine() because the end ‘finish’ never equalled the setup ‘finish’. So what’s going on…!!! Back to basics… used print statements on the objects and I could see the memory addresses were different… hmmm…

AHHHHH !!! The DICTIONARY in Map() actually makes the class instances of the rooms, once and only once, and those pointers are held in the dictionary.

NOW I get it. I had no idea that classes instances can be created in a dictionary until now. Wow… that’s really very clever once you understand it.

A free service run by Zed A. Shaw for learncodethehardway.org.