简体   繁体   English

在Python 3中创建引用字典中不同条目的动态函数

[英]Creating a dynamic function referring to different entries in a dictionary in Python 3

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. 字典中的几个子集已编号,此编号始终与上述代码中使用的mapLocation#()相同。 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? 关于如何做到这一点有什么想法吗?

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. 您可以在类级别存储共享字典,并为每个对象实现不同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM