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

Python父类列表属性访问异常:子类实例报错AttributeError

解决子类实例访问父类step属性时的AttributeError

错误重现

Traceback (most recent call last):
  File "C:\digitalEqualization\main.py", line 27, in <module>
    lms_eq = eq.lms(number_of_taps=6, step=0.1,
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\digitalEqualization\equalizer\lms.py", line 9, in __init__
    super().__init__(number_of_taps, step, sample_rate, bit_rate, alphabet, variable_step)
  File "C:\digitalEqualization\equalizer\equalizer.py", line 30, in __init__
    self.configure_step(step)
  File "C:\digitalEqualization\equalizer\equalizer.py", line 72, in configure_step
    self.step.append(new_step)
    ^^^^^^^^^
AttributeError: 'lms' object has no attribute 'step'

问题根源

父类equalizer中的step: []是类型注解语法,仅用于提示变量类型,并没有实际初始化实例级别的step属性。当子类实例调用configure_step方法尝试执行self.step.append时,由于实例本身未创建step属性,因此抛出AttributeError。

另外,即使将step定义为类属性(比如step = []),所有实例会共享同一个列表,这不符合你“记录每个lms对象所有步长值”的需求——多个实例的步长记录会互相干扰。

解决方案

在父类的__init__方法中初始化实例专属的step列表,确保每个实例拥有独立的步长记录容器:

修改后的父类代码

class equalizer:
    """
    Class equalizer
    """
    step: list[float]  # 规范的类型注解(Python 3.9+),低版本可改用 List[float](需 from typing import List)
    step_min: float                 # Minimum step
    step_max: float                 # Maximum step
    _variable_step: bool            # Authorize variable step
    

    def __init__(self, number_of_taps, step, sample_rate, bit_rate, alphabet, variable_step):
        self.step = []  # 初始化实例级别的空列表
        self.configure_step(step)
        self._variable_step = variable_step
      

    def configure_step(self, new_step=-1):
        """
        Update the step
        :param new_step:
        :return: None
        """
        if new_step > 0:
           self.step.append(new_step)
        else:
            raise Exception("StepValue: the step value has to be greater than 0.")

额外优化建议

  • 类型注解适配:若使用Python 3.9以下版本,需先导入List类型:
    from typing import List
    
    再将step: list[float]改为step: List[float]。
  • 父类中未使用的参数(如number_of_taps、sample_rate等)可以按需处理,避免代码冗余。

验证

修改后,子类lms实例化时,父类__init__会先创建实例专属的step列表,再调用configure_step添加初始步长,即可正常运行,每个lms对象会独立记录自己的步长历史。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:27:43