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

如何在函数内使用字典?跨文件跨函数调用该字典可行吗?

解决方法

首先要解决几个核心问题:让storage函数能对外暴露字典、修正计算函数的语法错误、实现跨Notebook的导入和调用。

1. 修正data_storage.ipynb中的storage函数

原函数里的dictionary是局部变量,外部无法访问,必须让函数返回这个字典:

def storage():
    dictionary = {
        'server_price': 100,
        'server_rack': 30, 
        'connections': 50  # 修正原拼写错误conections为connections
    }
    return dictionary  # 返回字典,供外部调用

2. 在主环境中导入并使用字典

针对Notebook文件,有两种常用导入方式:

方式一:使用%run魔法命令(Jupyter专属)

在主Notebook中执行:

# 运行data_storage.ipynb,加载其中的函数
%run data_storage.ipynb

# 调用storage函数获取字典
cost_dict = storage()
print(cost_dict['server_price'])  # 输出100

方式二:转成Python文件后导入

  1. 把data_storage.ipynb导出为data_storage.py(Jupyter中通过「文件>下载为>Python(.py)」实现)
  2. 在主脚本/Notebook中导入:
from data_storage import storage

cost_dict = storage()

3. 让calculate_final.ipynb的计算函数使用该字典

先修正原计算函数的语法错误(参数写法、函数调用、return缺失、键名引号等问题),再让函数支持使用字典:

# calculate_final.ipynb中的修正后代码
def calteam(number_of_servers):
    return number_of_servers * (1/5)  # 增加return返回计算结果

def price_team(team_count):
    return calteam(team_count) * 200  # 正确调用calteam函数,增加return

def calculate_total(price_team_val, servers, server_racks, connections, cost_dict):
    # 使用传入的cost_dict获取单价
    server_total = servers * cost_dict['server_price']
    # 计算总价并返回
    return price_team_val + server_total + (server_racks * cost_dict['server_rack']) + (connections * cost_dict['connections'])

调用计算函数的两种方式

  • 方式一:字典作为参数传入(推荐,符合函数封装原则)
    在导入两个文件的主环境中执行:

    %run data_storage.ipynb
    %run calculate_final.ipynb
    
    cost_dict = storage()
    team_num = calteam(10)
    team_price = price_team(team_num)
    total = calculate_total(team_price, 5, 2, 10, cost_dict)
    print(total)  # 输出1460(计算逻辑:(10*0.2)*200 +5*100 +2*30 +10*50)
    
  • 方式二:计算函数内部直接获取字典
    修改calculate_final.ipynb中的函数,直接在内部导入并获取字典:

    # 先导入storage函数
    from data_storage import storage
    
    def calculate_total(price_team_val, servers, server_racks, connections):
        cost_dict = storage()
        server_total = servers * cost_dict['server_price']
        return price_team_val + server_total + (server_racks * cost_dict['server_rack']) + (connections * cost_dict['connections'])
    

4. 最终整合方案

如果要把所有逻辑整合到主Notebook,按以下步骤执行:

  1. 运行%run data_storage.ipynb和%run calculate_final.ipynb加载所有函数
  2. 按业务流程调用:
# 1. 获取成本字典
cost_dict = storage()
# 2. 计算团队相关费用
server_qty = 15
team_count = calteam(server_qty)
team_cost = price_team(team_count)
# 3. 计算总费用
total_cost = calculate_total(team_cost, server_qty, 3, 15, cost_dict)
print(f"总费用:{total_cost}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:59:51