1

I have the following function:

def mapLocation1():
if rooms[1]["mapLoc"] == rooms[currentRoom]["mapLoc"]:
    #return(stuff)
elif "item" in rooms[1]:
    #return(stuff)
else:
    #return(stuff)

This particular function can see use several times in my program up to perhaps three dozen times. Of course, copying the above function that many times doesn't make for nice code, is a hassle to alter and it's likely going to be expanded anyway, so I want to make it a dynamic function. However, the issue is that with my code I'm referring to a dictionary I've set up elsewhere. This dictionary looks something like this:

rooms = {
        1 : {
            "mapLoc"    : 1,
            #MoreStuff
            },

        2 : {
            "mapLoc"    : 2,
            #MoreStuff
            },
        }

The several subsets in the dictionary are numbered, with this number always being the same as the mapLocation#() used in the above code. The entries in the dictionary have to be defined by hand due to the nature of their content, but if I can make the function dynamic rather than writing several dozen functions that are identical aside from a number that is mentioned thrice takes up too much space for my liking. Using the answer to this question I found the following code to make a function dynamic:

def makefunc(val):
    def somephase():
        return '%dd' % (val,)
    return somephase

Phase2 = makefunc(2)
Phase3 = makefunc(3)

However, I've tried to combine this with my function to make it dynamic, but thus far I've had no luck. Are there any ideas as to how I can do this?

Community
  • 1
  • 1
Thomas Jacobs
  • 171
  • 2
  • 10

1 Answers1

0

How about using instances and classes in order to achieve this?

You can store the shared dictionary at the class level and also implement different behaviour for each object.

sorin
  • 161,544
  • 178
  • 535
  • 806