[英]How can I associate dictionary keys with functions?
My application has a class full of functions that perform various operations. 我的应用程序有一个完整的函数类,可以执行各种操作。 These operations are related to 1 and only 1 dictionary key. 这些操作与1和仅1个字典键相关。 How can I associate the dictionary key with its respective function? 如何将字典键与其各自的功能相关联? The goal of the tool will be for it to use the appropriate set of functions when given a set of keys. 该工具的目标是在给定一组键时使用适当的函数集。
This is how I currently work it out: 这就是我目前的工作方式:
class MyClass:
def FuncA(self):
# Some code -----------------------------
def FuncB(self):
# Some code -----------------------------
myDict["Objective A"] = MyClass.FuncA()
myDict["Objective B"] = MyClass.FuncB()
Due to the nature of my program, the set of keys that will be used can change from time to time. 由于我的程序的性质,将使用的密钥集可能会不时更改。 Therefore, hard coding it as I have makes no sense. 因此,对我进行硬编码是没有意义的。 I want to be able to loop through my set of keys and run the appropriate functions. 我希望能够遍历我的一组键并运行适当的函数。 Remember, ObjectiveA is associated with FuncA. 请记住,ObjectiveA与FuncA相关联。 Therefore, if ever ObjectiveA was to appear in my list of keys, FuncA would need to be called in order to process some operation and populate the respective value pair. 因此,如果ObjectiveA出现在我的密钥列表中,则需要调用FuncA以处理某些操作并填充相应的值对。
Envisioning this: 想象一下:
for k in myDict.keys():
myDict[k] = MyClass.TheAssociatedFunction()
myDict["Objective A"] = MyClass.FuncA()
associates the return value of MyClass.FuncA
. 关联MyClass.FuncA
的返回值。 If you want to associate the function itself: 如果要关联函数本身:
myDict["Objective A"] = MyClass.FuncA
myDict["Objective B"] = MyClass.FuncB
Then you can call it directly: 然后你可以直接调用它:
myDict["Objective A"]()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.