如何解决Python中循环导入导致的'initialize未定义'错误?
问题原因:循环导入导致函数未定义
你的代码出现name "initialize" is not defined错误,核心原因是循环导入:
- main.py开头执行
from file2 import *,尝试导入file2的所有内容 - 但file2.py又执行
from main import *,反过来导入main的所有内容 - 这种互相导入会打乱Python的模块加载顺序,当main.py试图获取initialize函数时,file2还在加载main的过程中,initialize函数还没被定义,因此报错。
解决方案
1. 打破循环导入,移除不必要的全局导入
删除file2.py中的from main import *,不要依赖全局导入来获取变量,改用参数传递的方式。
2. 修改file2.py代码
将initialize函数改为接收参数的形式,直接使用传入的数值:
# file2.py def initialize(num_cpus): cpu_count = int(num_cpus) if cpu_count == 1: print(num_cpus) elif cpu_count == 2: print(num_cpus) else: print(num_cpus)
3. 修改main.py中的函数调用
在setup函数里调用initialize时,传入numCPUs变量:
if usrInput == "y" : initialize(numCPUs) # 传入numCPUs作为参数
4. 修正main.py中的小错误
main.py里导入了from os import system, name,所以调用清屏命令时不需要加os.前缀,直接使用:
system("cls" if name == "nt" else "clear")
完整修正后的代码
main.py
# main.py from os import system, name from file2 import * # welcome function obtains username def welcome(): print("Welcome to UNO! Please enter your name:") global username username = str(input("")) # if the user's name is valid, continue. if not, restart if username.isalnum() == True: setup() else: print("Something went wrong. Make sure to include only alphanumeric characters in your name.") welcome() # setup function defines game rules # user can only enter number a number and the number cannot be more than 4 nor less than 1 def setup(): print("Enter how many CPUS you would like to play against (1-3):") global numCPUs numCPUs = input("") # determine if the user input is valid. if not, restart if numCPUs >= "1" and numCPUs <= "3": print("Hello there, " + username + """! In case you may have forgotten how to play UNO, here is a quick refresher: 1. Each player is given 7 random cards to start. The cards in your hand are visible to you only. Likewise, your opponents can see only their cards. 2. Once the game starts, a card is drawn at random from what remains in the deck after the initial serve and is laid on the table. 3. Once it becomes your turn to play, you will choose a card from your hand that depicts either the same number or color (or both) as the previous played card. You may also use a wild card if you have one. If you do not have a playable card, you must draw from the deck until you acquire a playable card (fun, right?). Ready? (y/es, n/o):""") usrInput = input("").lower() # determine if the user is ready to play if usrInput == "y": initialize(numCPUs) # 传入参数 else: system("cls" if name == "nt" else "clear") # 修正os调用 welcome() else: print("Something went wrong. Please enter a number between 1-3.") setup() # call the welcome function to start the process welcome()
file2.py
# file2.py def initialize(num_cpus): cpu_count = int(num_cpus) if cpu_count == 1: print(num_cpus) elif cpu_count == 2: print(num_cpus) else: print(num_cpus)
内容的提问来源于stack exchange,提问作者Gabe
相关产品推荐
相关产品推荐

