Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将多个变量从函数移动到全局范围?_Python_Python 3.x_Function_Variables - Fatal编程技术网

Python 如何将多个变量从函数移动到全局范围?

Python 如何将多个变量从函数移动到全局范围?,python,python-3.x,function,variables,Python,Python 3.x,Function,Variables,我是python新手,我正在创建一个类似垄断的游戏,我正在研究程序的设置方面,我有一个函数,询问用户在每个设置中需要输入什么,然后我使用另一个函数将这些设置导入到文本文件中,以便存储以备以后使用,并让用户使用程序作为设置。这就是我的问题所在,我预计会有大约15个问题,这是我唯一能想到的办法,将它们从函数中带出来,用于另一个函数,并将它们导入到全局范围,以便程序可以使用它们,是使用return,还有其他方法吗?还是我只需要对每个变量使用return 谢谢 # Settings file, if u

我是python新手,我正在创建一个类似垄断的游戏,我正在研究程序的设置方面,我有一个函数,询问用户在每个设置中需要输入什么,然后我使用另一个函数将这些设置导入到文本文件中,以便存储以备以后使用,并让用户使用程序作为设置。这就是我的问题所在,我预计会有大约15个问题,这是我唯一能想到的办法,将它们从函数中带出来,用于另一个函数,并将它们导入到全局范围,以便程序可以使用它们,是使用return,还有其他方法吗?还是我只需要对每个变量使用return

谢谢

# Settings file, if user chooses to run setup this is all the setup 
questions
def gameSettingsSetup():
   print("Lets setup")
   numPlayers = int(input("How many real players are playing: "))
   numAIplayers = int(input("How many AI players will be playing?: 
   "))
   AILevel = input("What AI difficulty level would you like?: ") 

# Game settings all the main game settings

# sends over the settings into the text file
def gameSettingsSave():
通过使用
global
可以将全局变量拉入函数并修改它们

你可以这样做

返回numPlayers、nummaiplayers、AILevel
但将所有设置存储在字典中可能更容易:

def gameSettingsSetup():
打印(“让我们设置”)
设置={}
设置[“numPlayers”]=int(输入(“有多少真正的玩家在玩:”)
设置[“numAIplayers”]=int(输入(“将有多少AI玩家参与游戏?:”)
设置[“AILevel”]=输入(“您想要什么AI难度?:”)
返回设置

然后,您可以将
设置
字典传递给任何需要它的函数,也可以轻松地将其全部保存到磁盘。

不要使用
全局
跨方法共享变量;将它们改为对象属性

class Game:

    def __init__(self):
        self.questions = []
        self.ai_level = 'easy'
全局性导致方法之间的耦合,这很难解释。 今天,您可以理解代码, 但在它生长几个星期后,它将是一种完全不同的野兽

另外,请遵循的关于方法和变量名使用
snake\u case
的建议:

    def game_settings_setup(self):
        print("Let's setup.")
        self.num_players = int(...)
        self.num_ai_players = int(...)
        self.ai_level = ...
帮你自己一个忙。 运行
$pip install flake 8
,然后运行
$flake 8*.py
以获取有关您编写的代码的提示。 按照flake8的建议,进行建议的编辑。

您可以使用全局变量,但不应返回包含所选配置设置的对象。然后,
gameSettingsSetup
的调用方可以决定如何处理它:将其保存为全局变量,将其解压为多个全局变量,等等。
    def game_settings_setup(self):
        print("Let's setup.")
        self.num_players = int(...)
        self.num_ai_players = int(...)
        self.ai_level = ...