Python导入循环和顶级程序结构

Python导入循环和顶级程序结构,python,design-patterns,import,Python,Design Patterns,Import,为了帮助我学习Python,我正在构建一个简单的基于文本的小游戏。我正在研究文件的粗略的最高层次结构。到目前为止,我有main.py、input.py和commands.py main.py from input import * x = 1 start() from commands import * def inputLoop(): inString = input('::> ') tokens = inString.split(' ') cmd = tok

为了帮助我学习Python,我正在构建一个简单的基于文本的小游戏。我正在研究文件的粗略的最高层次结构。到目前为止,我有main.py、input.py和commands.py

main.py

from input import *
x = 1
start()
from commands import *

def inputLoop():
    inString = input('::> ')
    tokens = inString.split(' ')
    cmd = tokens[0]
    args = tokens[1:]
    if cmd != '':
        try:
            commands[cmd](args)
        except KeyError:
            print('Command not found.')
        print('\n')
    inputLoop()

def start():
    inputLoop()
def quit(arg):
    input('Goodbye!')
    exit()

def echo(arg):
    print(' '.join(arg))

commands = {
    'exit' : quit,
    'echo' : echo
}
input.py

from input import *
x = 1
start()
from commands import *

def inputLoop():
    inString = input('::> ')
    tokens = inString.split(' ')
    cmd = tokens[0]
    args = tokens[1:]
    if cmd != '':
        try:
            commands[cmd](args)
        except KeyError:
            print('Command not found.')
        print('\n')
    inputLoop()

def start():
    inputLoop()
def quit(arg):
    input('Goodbye!')
    exit()

def echo(arg):
    print(' '.join(arg))

commands = {
    'exit' : quit,
    'echo' : echo
}
命令.py

from input import *
x = 1
start()
from commands import *

def inputLoop():
    inString = input('::> ')
    tokens = inString.split(' ')
    cmd = tokens[0]
    args = tokens[1:]
    if cmd != '':
        try:
            commands[cmd](args)
        except KeyError:
            print('Command not found.')
        print('\n')
    inputLoop()

def start():
    inputLoop()
def quit(arg):
    input('Goodbye!')
    exit()

def echo(arg):
    print(' '.join(arg))

commands = {
    'exit' : quit,
    'echo' : echo
}
可以看到main.py导入input.py,它导入commands.py。这一切都很好,我可以有效地将文本输入映射到函数,并成功地传递参数。我遇到的问题是如何使main.py中声明的变量可供commands.py中的函数访问。如果我从commands.py导入main.py,它将创建一个导入循环。我知道我缺少了一些高层次的设计模式来把整个事情结合在一起

也许我创建了一个主类、一个导入类和一个commander类,并通过每个构造函数向下传递主类的实例,直到commander类可以引用它,但这对我来说似乎很笨拙和不雅观


您将如何构造此程序?

将变量分离到“settings.py”中,并在需要访问时导入该变量,如何

虽然我更喜欢在一些名为设置或选项的类中管理它们,因为对其中一个的更改可能会级联到其他设置中

此外,如果访问局部范围(函数内部)内的全局变量,则必须将其声明为全局变量

s = 1
def func(x):
    global s
    s=2

否则,您只会生成一个名为s

的局部变量,我认为它更像是命令需要访问的玩家和敌人类的实例,但这也适用于此。谢谢你的建议!