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

导入含依赖的自定义类时出现'yf'未定义错误,求解决方法

解决方案

问题原因

ClassFile.py 中的 example_class 在初始化方法里使用了 yf 别名,但该文件本身并未导入 yfinance 库。Python模块的命名空间相互独立,工作文件中导入的 yf 不会共享给 ClassFile,因此触发 name 'yf' is not defined 错误。

修复方法

方法1:在ClassFile中直接导入依赖(推荐)

修改 ClassFile.py,在类定义前导入所需依赖,让模块自身管理依赖:

import yfinance as yf

class example_class:
    
    def __init__(self, ticker):
        self.df = yf.download(ticker, start='2020-12-31')
    
    def do_something(self):
        return something  # 注意:此处'something'需定义具体值或逻辑,否则会触发新的未定义错误

工作文件中正确导入类并实例化:

from ClassFile import example_class
# 工作文件如果自身不需要使用yfinance,可省略下面这行导入
import yfinance as yf

instance = example_class('MSFT')

方法2:将依赖作为参数传入初始化方法

若不想在 ClassFile 中硬编码导入,可将 yf 作为参数传入类的初始化方法:
修改 ClassFile.py:

class example_class:
    
    def __init__(self, ticker, yf):
        self.df = yf.download(ticker, start='2020-12-31')
    
    def do_something(self):
        return something

工作文件中调用时传入依赖实例:

import ClassFile
import yfinance as yf

instance = ClassFile.example_class('MSFT', yf)

额外注意事项

  • 确保已通过 pip install yfinance 命令安装了yfinance库;
  • 原代码中 do_something 方法返回的 something 未定义,需补充具体逻辑或变量值,否则运行时会触发新的未定义错误。

内容的提问来源于stack exchange,提问作者Jack_Greenaway

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:01:15