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

2024-10-02 22:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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语句。我能做些什么来让一个变量指向并运行一个方法

干杯

马克


Tags: 方法testifdefglobal指向printtest1
1条回答
网友
1楼 · 发布于 2024-10-02 22:30:09

您可以先创建一个函数字典,然后用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

相关问题 更多 >