从另一个文件中的函数导入文件

我需要调用我在另一个文件中的函数中创建的列表。我试图在下面尝试这个,但我收到了错误cannot import name 'names' from 'backend'。有谁知道如何在不上课的情况下实现这一目标?


import backend

from backend import names

word = names

print (word)

错误信息:


File "C:/Users/user/OneDrive/Desktop/Pokemon/weather.py", line 52, in <module>

  from backend import names

  builtins.ImportError: cannot import name 'names' from 'backend'

另一个文件的代码是


import const 


SEP = ','


def get_pokemon_stats():

    """Reads the data contained in a pokemon data file and parses it into

    several data structures.


    Args:

        None


    Returns: a tuple of:

        -a dict where:

            -each key is a pokemon name (str)

            -each value is a tuple of the following stats:

                -pokemon name (str)

                -species_id (int)

                -height (float)

                -weight (float)

                -type_1 (str)

                -type_2 (str)

                -url_image (str)

                -generation_id (int)

                -evolves_from_species_id (str)

        -a dict where:

            -each key is a pokemon species_id (int)

            -each value is the corresponding pokemon name (str)

        -a list of all pokemon names (strs)

        -a dict where:

            -each key is a pokemon type (str). Note that type_1 and type_2

            entries are all considered types. There should be no special

            treatment for the type NA; it is considered a type as well.

            -each value is a list of all pokemon names (strs) that fall into

            the corresponding type

    """

    name_to_stats = {}

    id_to_name = {}

    names = []

    pokemon_by_type = {}

    DATA_FILENAME = 'pokemon.csv' 

慕妹3242003
浏览 194回答 2
2回答

慕田峪7331174

根据Python 的文档:在 Python 中,仅在函数内部引用的变量是隐式全局变量。如果在函数体内的任何地方为变量赋值,则假定它是局部变量,除非明确声明为全局变量。因此,您不能names从另一个文件导入您的列表的原因是因为names它在您的get_pokemon_stats函数范围内并且它不是一个全局变量。您可以names将其设为 global 将其放在您的函数之外,并将其声明为 global 以在您的函数内使用:...names = []def get_pokemon_stats():&nbsp; &nbsp; ...&nbsp; &nbsp; global names&nbsp; &nbsp; ...但是,如果您真的想这样做,您应该仔细考虑。names一旦您调用您的get_pokemon_stats函数,将只包含实际值。尽管如此,如果您不真正了解局部和全局变量的工作原理以及何时应该使用它们,则应避免仅全局声明变量。我建议您考虑改为执行以下代码:from backend import get_pokemon_stats_, _, word, _ = get_pokemon_stats()print (word)

繁星点点滴滴

您需要调用该get_pokemon_stats函数。它返回四个值,第三个值是names。import backendname_to_stats, id_to_name, names, pokemon_by_type = backend.get_pokemon_stats()print(names)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python