0

我有两个文件。一个名为“variables.py”的函数在:

def get_players():
    '''
    (NoneType) -> Dictionary
    Asks for player names
    '''
    loop = True
    players = {}
    while loop == True:
        player = input("Enter player names: ")
        player = player.strip()
        if player in players or player == "":
            print("Choose a different name!")
        elif "player1" in players:
            players["player2"] = [player, 0]
        elif player not in players:
            players["player1"] = [player, 0]
        if len(players) >= 2:
            loop = False
    return players

同一目录中的另一个文件名为“game.py”,其中包含:

import variables
players = get_players()

当我尝试运行“game.py”时,NameError: name 'get_players' is not defined 为什么会出现此错误?!我已经尝试了一切!

4

3 回答 3

2

它应该是

players = variables.get_players()

由于您只导入了模块variables,而不是方法get_players

或者你也可以这样做:

from variables import get_players

players = get_players()

在此处阅读有关导入模块的更多信息

于 2013-10-14T18:08:32.983 回答
1

你已经导入了variables,没有get_players。您可以保持导入原样并调用variables.get_players(),也可以先执行from variables import get_players然后调用get_players()

这是 Python 中相当基本的事情:看起来你可以从基本教程中受益。

于 2013-10-14T18:08:45.093 回答
0

使用 Python,当您导入模块时,会创建一个具有该名称的模块变量,该名称是所有导入模块的变量所在的位置:

import variables
players = variables.get_players()

你也可以一个只引入该名称的模块中导入:

from variables import get_players
players = get_players()

您还可以执行以下操作从模块中导入所有名称,但不鼓励这样做,因为它会导致难以阅读的代码:

from variables import *
players = get_players()
于 2013-10-14T18:10:07.590 回答