首页 > 解决方案 > 从另一个文件的不同函数访问变量

问题描述

myfunctions.py在 mypythonlib 目录中有一个文件

from requests_html import HTMLSession
import requests

def champs_info(champname:str, tier_str:int):  
    url = f"https://auntm.ai/champions/{champname}/tier/{tier_str}"
    session = HTMLSession()
    r = session.get(url)
    r.html.render(sleep=1, keep_page=True, scrolldown=1)

    information = r.html.find("div.sc-hiSbYr.XqbgT")
    sig = r.html.find('div.sc-fbNXWD.iFMyOV')
    tier_access = information[0]
    tier = tier_access.text

我想tier通过另一个文件访问变量-test_myfunctions.py 但问题是我还必须为函数提供参数,champs_info以便它可以相应地访问 url。

from mypythonlib import myfunctions
def test_champs_info():
    return myfunctions.champs_info("abomination",6).tier

但是在运行此代码时,我收到了错误-

./tests/test_myfunctions.py::test_champs_info Failed: [undefined]AttributeError: 'NoneType' object has no attribute 'tier'
def test_champs_info():
>       return myfunctions.champs_info("abomination",6).tier
E       AttributeError: 'NoneType' object has no attribute 'tier'

tests/test_myfunctions.py:3: AttributeError

对此有任何解决方案,为什么此代码无法访问该变量?我写信myfunctions.champs_info("abomination",6).tier是希望它能够tier从函数中获取变量,champs_info同时为它提供 myfunctions 文件中所需的所有参数:(

标签: pythonfunctionnested-function

解决方案


在 myfunctions.champs_info() 添加返回层

并在脚本 test_myfunctions.py 中删除.tier


推荐阅读