Python函数的函数名250217

  • 函数名其实就是一个变量,这个变量就是代指函数而已
  • 函数也可以被哈希,所以函数名也可以当作集合中的元素,也可作为字典的key值
python 复制代码
# 将函数作为字典中的值,可以避免写大量的if...else语句
def fun1():
    return 123
def fun2():
    return 456
def fun3():
    return 789
def fun4():
    return "abc"
map_fun = {"1": fun1, "2": fun2, "3": fun3, "4": fun4}
print(map_fun.get(input("Key value"))())
python 复制代码
# 将函数名做为列表中的成员,可以使用循环来简化代码,避免硬编码
def f1():
    return 1
def f2():
    return 2
def f3():
    return 3
list_fun = [f1, f2, f3]
for v in list_fun:
    print(v)
  • 上述代码之所以能用,是因为函数参数为空,这样不同名字的函数可以统一调用代码,如果不同函数有不同的函数,是不是就束手无策了呢?
python 复制代码
def f1(a):
    return a;
def f2(a, b):
    return a, b
map_fun = {"1": [f1, 555], "2": [f2, [666, 777]]}
list_value = map_fun.get(input("key value"))
if list_value:
	list_value[0](*list_value[1])
python 复制代码
def f1(a):
    return a;
def f2(a, b):
    return a, b
list_fun =[{"name": f1, "params": {"a": 5}}, {"name": f2, "params": {"a": 6, "b": 7}}]
for v in list_fun:
    v.get("name")(**v.get("params"))
相关推荐
SelectDB3 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码10 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵21 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab