You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现函数调用另一函数作为参数 简化主代码

具体实现方法

要实现函数作为参数传递的调用效果,核心是去掉DetermineAge对全局变量的依赖,把获取年龄的逻辑通过参数传入即可,不需要在主代码里保留中间变量赋值。

修改后的完整代码

def GetAge():
   age = int(input("Please enter your age: "))
   return age
  
    
def DetermineAge(get_age_func):
    # 调用传入的年龄获取函数拿到输入值
    age = get_age_func()
    if age < 2:
        print("Stage of Life: A Baby")
    elif age < 4:
        print("Stage of Life: A Toddler")
    elif age < 13:
        print("Stage of Life: A Kid")
    elif age < 20:
        print("Stage of Life: A Teenager")
    elif age < 65:
        print("Stage of Life: An Adult")
    elif age >= 65:
        print("Stage of Life: An Elder")
    else:
        print("Mistakes were made, please restart the program and try again.")

# 主代码无需中间赋值,直接将GetAge作为参数传入即可
DetermineAge(GetAge)

改动点说明

  • 调整DetermineAge的函数定义,新增形参用于接收获取年龄的函数,彻底移除对全局变量age的依赖,避免全局变量带来的耦合问题
  • 在DetermineAge内部调用传入的函数,拿到用户输入的年龄值,后续的年龄阶段判断逻辑不需要做任何修改
  • 主代码删除age = GetAge()的全局赋值语句,直接把GetAge函数作为参数传入DetermineAge即可完成全部逻辑。如果需要主代码里同时出现两个函数的显式调用,也可以将调用语句写为DetermineAge(lambda: GetAge()),运行效果完全一致。

注意:传入GetAge作为参数时不要加括号,加括号会直接执行函数并把返回值(用户输入的整数年龄)传入,无法实现把函数本身作为参数传递的效果。

内容的提问来源于stack exchange,提问作者Mark Silkworth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 21:30:47