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

导入data_inputs.py函数时出现function与float不支持相乘的TypeError错误

问题根因
  • 命名冲突:你编写的elec_MJ、coal_MJ、oil_MJ三个工具函数,存在函数名、内部返回值变量名、参数名和全局变量多重重名的问题,会干扰Python的命名空间查找逻辑,导入时容易出现变量类型识别错误。
  • 顶层代码未做入口隔离:你在data_inputs.py顶层直接写了print调用语句,没有包裹if __name__ == "__main__"判断块。Python导入模块时会自动执行模块的所有顶层代码,导入阶段的命名空间和直接运行脚本的命名空间存在差异,就会触发本次的类型错误。
解决方案

按照以下步骤修改data_inputs.py即可解决问题:

  1. 调整工具函数的参数名、内部变量名,避免和函数名、全局变量重名,参考修改代码:
elec_kWh = 50000
gas_MJ = 0
coal_kg = 0
oil_L = 0

#%% 能耗单位转换工具函数
def elec_MJ(kwh_input):
    return kwh_input * 3.6

def coal_MJ(kg_input):
    return kg_input * 22.1

def oil_MJ(l_input):
    return l_input * 38.6

#%% 总能耗计算
def total_energy_consumption_MJ(elec_kWh_input, gas_MJ_input, coal_kg_input, oil_L_input):
    total_consumption = (elec_MJ(elec_kWh_input)+
                        gas_MJ_input +
                        coal_MJ(coal_kg_input) +
                        oil_MJ(oil_L_input)
                        )
    return total_consumption

# 仅直接运行当前脚本时执行打印,导入时跳过
if __name__ == "__main__":
    print(total_energy_consumption_MJ(elec_kWh, gas_MJ, coal_kg, oil_L))

def elec_percent_cons(elec_kWh_input, gas_MJ_input, coal_kg_input, oil_L_input):
    elec_percent = (
                    elec_MJ(elec_kWh_input) / 
                    total_energy_consumption_MJ(elec_kWh_input, gas_MJ_input, coal_kg_input, oil_L_input)
                    )
    return elec_percent
  1. 辅助检查:确认data_outputs.py中导入语句之前,没有定义和elec_kWh、gas_MJ等导入变量同名的函数、类,如果有需要重命名避免冲突。
  2. 清理缓存:删除项目目录下的__pycache__文件夹,避免旧的缓存代码影响运行。

修改完成后重新运行data_outputs.py即可正常导入变量和函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:24:01