为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3242003 2021-08-24 18:07:34
我需要调用我在另一个文件中的函数中创建的列表。我试图在下面尝试这个,但我收到了错误cannot import name 'names' from 'backend'。有谁知道如何在不上课的情况下实现这一目标?import backendfrom backend import namesword = namesprint (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' 
查看完整描述

2 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

根据Python 的文档:


在 Python 中,仅在函数内部引用的变量是隐式全局变量。如果在函数体内的任何地方为变量赋值,则假定它是局部变量,除非明确声明为全局变量。


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


您可以names将其设为 global 将其放在您的函数之外,并将其声明为 global 以在您的函数内使用:


...

names = []

def get_pokemon_stats():

    ...

    global names

    ...

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


我建议您考虑改为执行以下代码:


from backend import get_pokemon_stats

_, _, word, _ = get_pokemon_stats()

print (word)


查看完整回答
反对 回复 2021-08-24
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

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


import backend

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

print(names)


查看完整回答
反对 回复 2021-08-24
  • 2 回答
  • 0 关注
  • 193 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号