简体   繁体   English

如何将字典键与函数关联?

[英]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.

相关问题 我如何记录函数参数的字典键? - How can i document dictionary keys for a functions argument? 如何将特定的字典键与类列表中的对象相关联? - How can I associate a specific dictionary key to an object in a list of classes? 如果我在 Python 中有一个带有 2 个键的字典,我如何实现诸如 mean.median 和variance 之类的函数? - How Can I implement functions like mean.median and variance if I have a dictionary with 2 keys in Python? 如何将 3 个列表映射到字典键 - How can I map 3 lists to dictionary keys 如何向字典添加新键? - How can I add new keys to a dictionary? 当所有句子的关键字都包含在字典中时,如何将句子与字典相关联? - How can i associate a sentence to a dictionary when all the sentence's keywords are contained in the dictionary? 如何从嵌套字典创建平面字典,其字符串是引用字典的子集? - How can I create a flat dictionary from a nested dictionary whose keys are a subset of a reference dictionary? 如何添加所有键的值并打印新词典? - How can I add all keys' values and print the new dictionary? 如何将嵌套的字典键转换为字符串? - How can I convert nested dictionary keys to strings? 如何在密匙字典中找到最小值和密匙? - How can i find the minimum value and key in a scipy dictionary of keys?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM