导入文件后的NameError

时间:2013-10-14 18:06:21

标签: python

我有两个文件。一个名为“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 为什么?!我已经尝试了一切!

3 个答案:

答案 0 :(得分:2)

应该是

players = variables.get_players()

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

或者您也可以这样做:

from variables import get_players

players = get_players()

详细了解importing modules here

答案 1 :(得分:1)

您已导入variables,而不是get_players。您可以保持导入不变并致电variables.get_players(),或者from variables import get_players,然后拨打get_players()

这在Python中是一个相当基本的东西:看起来你可以从基础教程中受益。

答案 2 :(得分:0)

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

import variables
players = variables.get_players()

您还可以从导入模块,该模块将自行引入该名称:

from variables import get_players
players = get_players()

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

from variables import *
players = get_players()