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
相关产品推荐
相关产品推荐

