Python OOP中使用__div__魔法方法触发TypeError错误求助
解决自定义类除法运算的TypeError错误
问题根源
Python 3中,/运算符对应的魔法方法是__truediv__,你使用的__div__是Python 2的遗留方法,Python 3不再通过它处理/运算,因此触发类型错误。
修复方案
将类中的__div__方法替换为__truediv__,同时建议添加类型检查,避免传入非add_object实例时出现属性错误:
class add_object: def __init__(self, num) -> None: self.x = num def __truediv__(self, other): if isinstance(other, add_object): return self.x / other.x raise TypeError("Unsupported operand type for /") n1 = add_object(24) n2 = add_object(12) print(n1 / n2) # 输出: 2.0
可选扩展:支持反向除法
如果需要处理类似3 / n1这种左操作数不是add_object实例的场景,可以额外实现__rtruediv__方法:
def __rtruediv__(self, other): if isinstance(other, (int, float)): return other / self.x raise TypeError("Unsupported operand type for /")
内容的提问来源于stack exchange,提问作者Anik Saha
相关产品推荐
相关产品推荐

