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

Python类中如何判断对象类型实现同类实例的比较功能

代码修复方案

报错原因

isinstance() 函数的第二个参数要求传入类对象,原代码中传入的 self 是类的实例对象,不符合参数规范,因此触发运行错误。

修复后的完整代码

class A():
    def __init__(self,a):
        self.var = a
        
    def comparison(self,other):
        # 将isinstance第二个参数改为type(self),获取当前实例对应的类
        if not isinstance(other, type(self)):
            raise Exception("You are not comparing apples to apples")
        else:
            if self.var == other.var:
                print('we are equal')
            else:
                print('we are different')

运行效果

你提供的测试用例运行后完全符合预期:

  • 调用first.comparison(second) 输出:we are different
  • 调用first.comparison(third) 输出:we are equal
  • 调用first.comparison(fourth) 抛出指定异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:27:01