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

Python导入其他文件函数时避免原文件输出及解决变量未定义问题

问题根源与解决方案

Let's break down what's happening here and fix it without needing new files.

Why you're seeing f1's output when running f2

When you use from f1 import *, Python executes every line of code in f1 to load its contents into f2's scope. That means the y = fS(a,b), print(y), w = fM(a,b,y), and print(w) lines in f1 run during the import, which is why you see f1's 7 and 84 alongside f2's results.

Why moving a and b into if __name__ == '__main__': caused an error

The if __name__ == '__main__': block only runs when you execute f1 directly (e.g., python f1.py). When f2 imports f1, this block doesn't run—so if you put a = 3 and b = 4 inside it, those variables never get defined in f1's global scope. The line y = fS(a,b) (which was still in f1's global scope) tries to access a and b that don't exist, hence the "name not defined" error.

The fix: Move execution code (not function definitions) into the guard block

You only need to wrap the code that runs when f1 is executed directly into the if __name__ == '__main__': block. Keep your function definitions in the global scope so they can be imported by f2. Here's the corrected f1:

# Keep function definitions global so they're importable
def fS(a,b):
    x = a+b
    return x

def fM(a,b,y):
    z = a*b*y
    return z

# Only run this code when f1 is executed directly, not when imported
if __name__ == '__main__':
    a = 3
    b = 4
    y = fS(a,b)
    print(y)
    w = fM(a,b,y)
    print(w)

How this works:

  • When you run python f1.py, __name__ equals '__main__', so the block runs and you get the original output (7 84).
  • When f2 imports f1, only the function definitions are loaded—none of the code inside the guard block runs, so f1's print statements don't execute.
  • Your f2 code stays exactly the same: when it calls fS(c,d) and fM(c,d,p), it uses the arguments you pass (not any global variables from f1), so you'll only see f2's output (12 420).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:12:47