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

Python中如何从main.py向模块导入变量(不可修改main.py)

统计输入回文的模块调用问题

需求说明

  • 作为Python新手,开发统计用户输入中所有回文的程序
  • 必须使用模块结构
  • 要求从不可修改的main.py中把变量inp和count导入到modules.py中
  • 示例输入:sis Hannah is the name of the nun who talked to mom
  • 示例输出:There were 4 palindromes.

当前代码问题

现有代码能运行,但因为main.py和modules.py各自调用了input(),导致需要按两次回车才能完成输入。

不可修改的main.py代码

from modules import palindrome_check as pc, print_output as po

inp = input()
count = pc(inp)
po(count)

当前modules.py代码

def palindrome_check(inp):
    return inp == inp[::-1] if len(inp) > 1 else None

inp = [i for i in input().lower().split() if palindrome_check(i)]
count = 0
for i in inp:
    if palindrome_check(i):
        count += 1
def print_output(num):
    if count == 0:
        print("There were no palindromes.")
    else:
        if count == 1:
            print("There was one palindrome.")
        else:
            print("There were {} palindromes.".format(count))

尝试修改后遇到的错误

修改modules.py试图导入main.py的inp和count时,持续触发循环导入错误:

ImportError: cannot import name 'inp' from partially initialized module 'modules' (most likely due to a circular import)

已查阅视频和论坛,尝试过import *等方式,仍无法解决。

解决方案

核心问题是循环导入和模块职责混乱,modules.py不该自行读取输入,应该通过函数参数接收main.py传递的数据,重新梳理模块职责即可解决:

修改后的modules.py

def palindrome_check(word):
    # 仅负责单个单词的回文判断,统一转小写避免大小写干扰
    if len(word) <= 1:
        return False
    return word.lower() == word.lower()[::-1]

def count_palindromes(input_str):
    # 接收输入字符串,拆分后统计回文数量
    words = input_str.split()
    count = 0
    for word in words:
        if palindrome_check(word):
            count += 1
    return count

def print_output(num):
    # 根据统计数量输出对应文本
    if num == 0:
        print("There were no palindromes.")
    elif num == 1:
        print("There was one palindrome.")
    else:
        print(f"There were {num} palindromes.")

修改逻辑说明

  1. 避免循环导入:modules.py不再尝试导入main.py的变量,而是通过函数参数接收数据,符合模块的调用逻辑
  2. 职责拆分清晰:
    • palindrome_check:只做单个单词的回文判断,处理大小写问题(比如示例中的Hannah)
    • count_palindromes:接收输入字符串,拆分后统计回文数量,对应main.py中调用的pc(inp)
    • print_output:根据统计结果输出对应文本,完全适配原有调用结构
  3. 适配不可修改的main.py:不需要改动main.py的任何代码,运行时只需要输入一次,就能得到正确的统计结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:52:58