gpt4 book ai didi

python - 如何指向给定变量python的方法

转载 作者:行者123 更新时间:2023-12-01 03:53:33 24 4
gpt4 key购买 nike

possibleRequests = ['test', 'test1']

def inboxReader():
global inbox
tempInbox = []
tempInbox = inbox.inboxMessage #inboxMesage remains filled?
print(inbox.inboxMessage, 'inboxReader')
i = 0
while (i < len(tempInbox)):
if (tempInbox[i] in possibleRequests):
print('THIS IS WORKING')
#print(i)
i+=1

我希望能够让可能的请求指向要运行的方法,而不是拥有一长串 if 语句。为了让变量指向并运行一个方法,我能做什么。

干杯,

马克

最佳答案

您可以首先创建一个函数字典,然后使用 tempInbox[i] 引用它。示例代码如下:

def func_a(x):
return x

def func_b(x):
return x*10

tempInbox = (2,3)

fn_dict = {"a":func_a,"b":func_b}
print fn_dict["a"](tempInbox[0]) # returns 2
print fn_dict["b"](tempInbox[1]) # returns 30

关于python - 如何指向给定变量python的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37893005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com