繁体   English   中英

跨模块的Python用户定义的全局变量:运行其他模块时调用它们的问题

[英]Python User-Defined Global Variables Across Modules: Issues calling them when other modules are run

我对Python相当陌生,目前正在学习在python程序中使用函数和多个模块。

我有两个模块“ Functions_Practice_Main”(运行菜单)和“ Functions_Practice”,其中包含一个简单程序的代码,该程序可以计算出用户的输入是否除以7(我知道...相当愚蠢的做法)。

我想做的是让用户在运行菜单模块时输入其名称,然后通过显示整个程序来获取此全局变量,以使程序更具个性。

但是,当我运行菜单模块时,它会要求输入两次名称。 输入的名字显示在“ 7分频”程序中,输入的名字显示在菜单中。 我知道为什么会发生这种情况(由于导入了Functions_Practice模块,要求在其余代码有机会运行之前先知道Functions_Practice_Main模块中的全局变量是什么),但我确实需要知道如何解决此问题。

运行菜单模块时,如何使用户输入名称ONCE,然后通过显示整个程序来获取此全局变量,以使其对用户更具个性。

功能_实践_主要

import Functions_Practice, sys


name = input("What is your name? ")

def main():

while True:

  print(name, "'s Menu")
  print("*******************")
  print("1. Can you divide by 7?")
  print("2. Quit")
  print("*******************")
  selection = int(input("Your number selection please..."))

  if selection == 1:
    Functions_Practice.main()
  elif selection == 2:
    sys.exit()
  else:
    print("Your number selection was invalid, please try again...")


 if __name__ == '__main__':
    main()

* 函数实践*

import Functions_Practice_Main

def inputData(name):
    print(name)
    number = int(input(" Please enter your number: "))
    return number

def processData(number):
    answer = number % 7
    if answer == 0:
        remainder = True
    else:
        remainder = False
    return remainder

def outputData(remainder):
    if remainder == True:
        print("The number you entered doesn't have a remainder")
    elif remainder == False:
        print("The number you entered does have a remainder")



def main():
    number = inputData(Functions_Practice_Main.name)
    remainder = processData(number)
    outputData(remainder)


if __name__ == '__main__':
    main()

将模块作为脚本运行并不算将其作为模块导入。 当Functions_Practice_Main.py脚本导入Functions_Practice,而Functions_Practice导入Functions_Practice_Main时,Python不在乎Functions_Practice_Main.py中的代码已作为主脚本运行。 Python将再次运行它以生成模块。

您如何解决这个问题? 好吧,您应该做几件事。 首先,尽可能避免循环进口。 而不是让Functions_Practice导入Functions_Practice_Main,而是将来自Functions_Practice_Main的所有数据Functions_Practice需要作为函数参数。

在Functions_Practice_Main中:

Functions_Practice.interactive_remainder_test(name)

在Functions_Practice中:

def interactive_remainder_test(name):
    number = inputData(name)
    remainder = processData(number)
    outputData(remainder)

其次,是这样的:

name = input("What is your name? ")

属于文件main ,因为它们在导入文件时不应运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM