[python]TypeError: unsupported operand type(s) for /: ‘int‘ and ‘IntervalMath‘

博客讲述了如何在自定义的IntervalMath类中实现__truediv__和__rdiv__操作,区别在于a/2能调用内置函数,而2/a需要显式类型转换。作者对这种行为的原因进行了探讨,涉及Python的运算符优先级和类型转换规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义类型IntervalMath的实例a,求a/2可以进入类的内置函数__truediv__,而2/a进不去__rdiv__,只能在外面将2转化为IntervalMath类型。
否则会报错:TypeError: unsupported operand type(s) for /: ‘int’ and 'IntervalMath’
但a/2时就不会报错。

# -*- coding: utf-8 -*-
"""
Created on Wed Mar  9 21:10:37 2022

@author: REESE
"""
class IntervalMath:
    def __init__(self,lower=0,upper=0):
        self.lo = float(lower)
        self.up = float(upper)
    
    def __add__(self,other):
        a,b,c,d = self.lo,self.up,other.lo,other.up
        
        #方法1
        #return IntervalMath(a+c,b+d) #相当于new了一个IntervalMath实例
    
        #方法2
        I = IntervalMath() #__init__函数参数有默认值,此时有();若无默认值,声明一个没有参数的实例时,不加()
        I.lo = a + c
        I.up = b + d
        return I
    
    def __sub__(self,other):
        a,b,c,d = self.lo,self.up,other.lo,other.up
        return IntervalMath(a-d,b-c)
    
    def __mul__(self,other):
        if isinstance(other, (int, float)): #实用程序函数,用于检查对象是否为特定类型,此处为判断Object 'other'是否为int或者float中的一种
            other = IntervalMath(other, other) # 例:other==2 ==》 other == I[2,2]
        a,b,c,d = self.lo,self.up,other.lo,other.up
        x,y = min(a*c,a*d,b*c,b*d), max(a*c,a*d,b*c,b*d)
        return IntervalMath(x,y)
    
    def __rmul__(self,other): #针对2*y0
        if isinstance(other, (int,float)):
            other = IntervalMath(other,other)
        return other*self
    
    def __truediv__(self,other):
        if isinstance(other,(int,float)): #为了实现a/2
            other = IntervalMath(other,other)
        a,b,c,d = self.lo,self.up,other.lo,other.up
        if c*d == 0:
            return 'error'
        else:
            x,y = min(a/c,a/d,b/c,b/d), max(a/c,a/d,b/c,b/d)
            return IntervalMath(x,y)
    
    def __rdiv__(self,other):#针对2/a
        #if isinstance(other,(int,float)): #为了实现2/a
        #    other = IntervalMath(other,other)
        return other/self
        '''a, b, c, d = other.lo, other.up, self.lo, self.up
        if c * d == 0:
            return 'error'
        else:
            x, y = min(a / c, a / d, b / c, b / d), max(a / c, a / d, b / c, b / d)
            return IntervalMath(x, y)'''
    
    #打印区间
    def __str__(self):
        return '[%g, %g]' % (self.lo, self.up)

a = IntervalMath(4,5)
print((a*2).lo,(a*2).up)
print((2*a).lo,(2*a).up)
print((a/2).lo,(a/2).up)

#实现2/a
other = 2
other = IntervalMath(other,other)
print((other/a).lo,(other/a).up)
#但我有个疑问,为什么print((2/a).lo,(2/a).up) 进不去a的内置函数__rdiv__中,而只能先在外面把2转化为IntergralMath类型。而a/2不必如此

问题虽已解决,但还是不太明白原因,下周一跟老师讨论一下后补充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值