You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跨Python文件访问其他函数内部变量出现NoneType报错如何解决

问题原因
  • champs_info 函数没有显式设置返回值,Python中所有未定义return语句的函数执行结束后默认返回None,你试图访问None的tier属性自然触发属性不存在的报错。
  • 函数局部变量的访问逻辑有误:函数内部定义的tier是局部变量,仅在函数运行过程中存在,不可能直接通过「函数调用结果.变量名」的方式访问,除非你把变量封装到返回的对象/字典里,或者直接返回变量本身。
解决方案

方案1:直接返回tier变量(适配单返回值需求)

修改myfunctions.py中的champs_info函数,末尾新增返回语句:

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
    # 新增返回语句
    return tier

同步修改test_myfunctions.py的调用逻辑,无需再加.tier后缀:

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

方案2:返回封装结构,支持多属性访问(适配多返回值需求)

如果后续需要返回不止tier一个字段,可以选择返回字典或者自定义类实例:

用字典封装的写法

修改myfunctions.py:

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
    # 返回包含所有所需字段的字典
    return {
        "tier": tier,
        "sig_content": sig[0].text if sig else ""
    }

调用时用字典键取值即可:

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

用自定义类封装的写法(支持.tier方式访问)

如果要保留你原本函数调用.tier的写法,可以定义简单的数据类:

from requests_html import HTMLSession
import requests
from dataclasses import dataclass

# 定义返回数据结构
@dataclass
class ChampResult:
    tier: str
    # 其他需要返回的字段可按需添加

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
    # 返回类实例
    return ChampResult(tier=tier)

这时候你原本写的myfunctions.champs_info("abomination",6).tier就可以正常运行。

内容的提问来源于stack exchange,提问作者Dheeraj-Tech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:18:03