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

时间:2018-11-21 20:50:32

标签: python

我需要调用在另一个文件中的函数中创建的列表。我曾尝试在下面尝试此操作,但收到错误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' 


    with open(const.DATA_FILENAME) as f:
        header_to_col_num = parse_header(f)
        for line in f:
            info = line.split(const.SEP)
            name = (info[(header_to_col_num['pokemon'])])
            col_names = ('pokemon', 'species_id', 'height', 'weight', 'type_1', 
            'type_2',
            'url_image', 'generation_id', 'evolves_from_species_id',)
            value = [info[header_to_col_num[col]] for col in col_names]
            value[1] = int(value[1])
            value[2] = float(value[2])
            value[3] = float(value[3])
            value[7] = int(value[7])
            value = tuple(value)

            name_to_stats[name] = value

            species_id = int(info[(header_to_col_num['species_id'])])
            id_to_name[species_id] = name
            names.append(name)


        for name, info in name_to_stats.items():
            type1 = info[4]
            type2 = info[5]
            if type1 in pokemon_by_type:
                pokemon_by_type[type1].append(name)
            else:
                pokemon_by_type[type1] = [name]
            if type2 in pokemon_by_type:
                pokemon_by_type[type2].append(name)
            else:
                pokemon_by_type[type2] = [name]


        return name_to_stats, id_to_name, names, pokemon_by_type

2 个答案:

答案 0 :(得分:0)

根据Python's documentation

  

在Python中,仅在函数内部引用的变量是隐式全局的。如果在函数体内任何位置为变量分配了值,除非明确声明为全局变量,否则假定该变量为局部变量。

因此,您无法从另一个文件导入names列表的原因是因为namesget_pokemon_stats函数范围内,并且不是全局变量。

您可以将names设置为全局变量,并将其声明为在函数内部使用:

...
names = []
def get_pokemon_stats():
    ...
    global names
    ...

但是,如果您确实要这样做,则应该仔细考虑。一旦调用names函数,get_pokemon_stats将只包含实际值。但是,如果您不太了解局部和全局变量的工作方式以及何时使用它们,则应该避免仅全局声明变量。

我建议您考虑改用以下代码:

from backend import get_pokemon_stats
_, _, word, _ = get_pokemon_stats()
print (word)

答案 1 :(得分:0)

您需要调用get_pokemon_stats函数。它返回四个值,第三个值为names

import backend
name_to_stats, id_to_name, names, pokemon_by_type = backend.get_pokemon_stats()
print(names)