📜  Python - 将函数存储为字典值

📅  最后修改于: 2022-05-13 01:55:25.365000             🧑  作者: Mango

Python - 将函数存储为字典值

给定一个字典,将其键分配为函数调用。

案例 1:没有参数。

用于实现此任务的方法是,函数名称保留为字典值,并在使用键调用时添加方括号“()”。

Python3
# Python3 code to demonstrate working of 
# Functions as dictionary values
# Using Without params
  
# call Gfg fnc 
def print_key1():
    return "This is Gfg's value"
  
# initializing dictionary
# check for function name as key
test_dict = {"Gfg": print_key1, "is" : 5, "best" : 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# calling function using brackets 
res = test_dict['Gfg']()
  
# printing result 
print("The required call result : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Functions as dictionary values
# Using With params 
  
# call Gfg fnc 
def sum_key(a, b):
    return a + b
  
# initializing dictionary
# check for function name as key
test_dict = {"Gfg": sum_key, "is" : 5, "best" : 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# calling function using brackets 
# params inside brackets
res = test_dict['Gfg'](10, 34)
  
# printing result 
print("The required call result : " + str(res))


输出
The original dictionary is : {'Gfg': , 'is': 5, 'best': 9}
The required call result : This is Gfg's value

案例 2:使用参数

使用 params 调用的任务与上述情况类似,值在函数调用期间在括号内传递,就像在通常的函数调用中一样。

蟒蛇3

# Python3 code to demonstrate working of 
# Functions as dictionary values
# Using With params 
  
# call Gfg fnc 
def sum_key(a, b):
    return a + b
  
# initializing dictionary
# check for function name as key
test_dict = {"Gfg": sum_key, "is" : 5, "best" : 9}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# calling function using brackets 
# params inside brackets
res = test_dict['Gfg'](10, 34)
  
# printing result 
print("The required call result : " + str(res)) 
输出
The original dictionary is : {'Gfg': , 'is': 5, 'best': 9}
The required call result : 44