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

Delta_Viewer类减法运算类型判断失效问题求助

问题描述

我在名为Delta_Viewer的类中编写了如下代码:

class Delta_Viewer():
    def __init__(self, df):
        self.df : pd.Dataframe = df       
        self._columns = trade_types
    # init method, properties, etc up here
        
    def __sub__(self, other):
        if type(other) == Delta_Viewer:        
            new_df = self.df.sub(other.df, fill_value = 0)
            return Delta_Viewer(new_df)
        else:
            print(type(other), 'self:', type(self))            
            print(id(other), 'self:', id(self))            
            raise Exception(f'Delta Viewer can only be subtracted from another Delta_Viewer instance. passed: {type(other)}')    
            
    def __rsub__(self, other):
        return self.__sub__(other)

当尝试将两个Delta_Viewer实例相减时,却触发了异常。添加调试打印后,结果显示两者类型完全一致:

<class 'Sitka.Portfolio.delta_gamma.Delta_Viewer'> self: <class 'Sitka.Portfolio.delta_gamma.Delta_Viewer'>
1681758064352 self: 1681751071136

改用isinstance()进行类型判断也无效。补充:该类无装饰器,仅含4个返回self.df预定义函数的属性。

问题分析与解决

1. __rsub__方法逻辑错误

当前__rsub__直接调用self.__sub__(other)是完全错误的。__rsub__是Python用来处理other - self的特殊方法,你的实现相当于把它变成了self - other,这会导致:

  • 执行delta2 - delta1时,实际计算的是delta1 - delta2
  • 如果other是数值类型,会直接触发类型异常

正确的__rsub__实现应该反过来计算:

def __rsub__(self, other):
    if isinstance(other, self.__class__):
        new_df = other.df.sub(self.df, fill_value=0)
        return Delta_Viewer(new_df)
    # 可选:支持数值与实例相减的场景
    try:
        new_df = other - self.df
        return Delta_Viewer(new_df)
    except TypeError:
        raise Exception(f"Unsupported type for subtraction with Delta_Viewer: {type(other)}")

2. 类对象身份不一致导致判断失效

你遇到的"类型显示相同但判断不通过"的问题,核心原因是两个实例所属的类对象不是同一个——常见于模块被热重载(比如用importlib.reload),或者在不同上下文重复导入了模块,导致同一个类名对应了不同的类对象。

解决办法是改用self.__class__来做类型判断,而不是直接写类名:

def __sub__(self, other):
    if isinstance(other, self.__class__):        
        new_df = self.df.sub(other.df, fill_value=0)
        return Delta_Viewer(new_df)
    else:
        raise Exception(f'Delta Viewer can only be subtracted from another Delta_Viewer instance. passed: {type(other)}')

这样判断的是other是否和当前实例属于同一个类,不受模块重载的影响。

3. 额外检查点

  • 确认是否在运行时重新加载过包含Delta_Viewer的模块
  • 检查项目中是否有多个地方定义了同名的Delta_Viewer类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:35:27