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

Python绘图报AttributeError: NoneType无generate_plot属性

问题排查与修复

核心错误原因

代码共存在6处直接触发AttributeError的问题:

  • 抽象基类写法错误:使用@abstractmethod但未导入abc模块的ABC和abstractmethod,基类未继承ABC;抽象方法内未加raise关键字,仅写NotImplementedError不会抛出拦截异常
  • 子类定义语法错误:OpenCloseChart被定义为普通函数,而非继承Chart的子类,内部嵌套的generate_plot不会绑定到实例,调用时直接报方法不存在
  • 依赖缺失:DataFrame.iplot()是cufflinks库提供的pandas扩展方法,未安装导入cufflinks并初始化时,DataFrame无该属性
  • 参数传值错误:iplot的y、secondary_y参数接收列名字符串/列名列表,原代码传入ticker_df.Open序列、不存在的列名'Close Price ($)',不符合接口要求
  • 实例化逻辑错误:原调用代码OpenCloseChart(Chart(ticker_df, config_dict))是把基类实例传入普通函数,未创建正确的子类实例,无法访问属性方法

修复步骤

  1. 安装缺失依赖:
pip install cufflinks plotly
  1. 补全导入项,修正抽象基类写法
  2. 将OpenCloseChart改写为继承Chart的子类,正确实现generate_plot方法
  3. 修正config_dict的参数传值,传入正确的列名
  4. 初始化cufflinks,绑定pandas扩展
  5. 修正实例化逻辑,直接传入参数创建子类实例

修复后完整可运行代码

from typing import Dict, Any
from abc import ABC, abstractmethod
import streamlit as stl
import pandas as pd
import cufflinks as cf
# 初始化cufflinks离线模式
cf.go_offline()
cf.set_config_file(offline=True, world_readable=True)

class Chart(ABC):
    def __init__(self, dataframe: pd.DataFrame, config_dict: Dict[str, Any]):
        self._dataframe = dataframe
        self._config_dict = config_dict

    @abstractmethod
    def generate_plot(self) -> stl.plotly_chart:
        raise NotImplementedError("子类必须实现generate_plot方法")


class OpenCloseChart(Chart):
    def generate_plot(self) -> stl.plotly_chart:
        openCloseChart_fig = self._dataframe.iplot(
            y=self._config_dict['y_data'],
            secondary_y=self._config_dict['secondary_y'],
            secondary_y_title=self._config_dict['secondary_y_title'],
            xTitle=self._config_dict['xTitle'],
            yTitle=self._config_dict['yTitle'],
            title=self._config_dict['title'],
            asFigure=self._config_dict['asFigure'])
        return stl.plotly_chart(openCloseChart_fig)


def create_open_close_chart(ticker_df: pd.DataFrame, name: str,
                            start_date: str,
                            end_date: str) -> stl.plotly_chart:
    config_dict = {
        # y、secondary_y传实际存在的列名,不要传Series或自定义字符串
        'y_data': 'Open',
        "secondary_y": 'Close',
        'secondary_y_title': "Close Price ($)",
        "xTitle": "Date",
        "yTitle": "Open Price ($)",
        "title": f"Open and Close Price of {name} From {start_date} To {end_date}",
        "asFigure": True
    }
    # 正确实例化子类
    open_close_chart_obj = OpenCloseChart(ticker_df, config_dict)
    return open_close_chart_obj.generate_plot()

# 调用示例
# create_open_close_chart(df, company_name, df_actual_start_date, end_date)

参考截图

  • 报错截图:
    报错截图
  • 预期效果截图:
    预期效果截图

内容的提问来源于stack exchange,提问作者Jamiu S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:45:29