2017-05-09 59 views
-1

我使用python 3.6并且想创建一个Interval类。我试图做一个可以添加一个整数和一个intervall的add方法。到目前为止我设法生成用于 工作I =间隔(2,3) C = I + 1#C = [3,4]类和方法python

然而相反dosent工作

I =间隔的码(2,3) C = 1 + I#获取错误消息类型错误:不支持的操作数类型(一个或多个)为+: 'INT' 和 '间隔'

我为我的类和方法的代码是作为folow中

类间隔:

def __init__(self,start=None,end=None): 
     if end==None: 
      end=start 
     if start==None: 
      start=end 
     if start>end: 
      raise TypeError('left value must be smaller than right value') 

     self.start=start 
     self.end=end 

高清添加(个体经营,其他):

if isinstance(other,int):  
     s2,e2=other,other 
     s1,e1=self.start,self.end 

    elif isinstance(self,int): 
     s1,e1=self,self 
     s2,e2=other.start,other.end 


    else: 
     s2,e2=other.start,other.end 
     s1,e1=self.start,self.end 
    return Interval(s1+s2,e1+e2) 

如果我试图改变我的elif在Add方法,如果没有什么作品。有谁知道如何解决这个问题?

谢谢!

回答

0

没有试图运行你的代码,但在我看来,根据http://www.diveintopython3.net/special-method-names.html你可能想实现RADD方法。

第一个工作,因为您正在为Interval(I + 1)添加整数,并且Interval类的添加方法被调用。但是,在第二种情况下,您正在调用整数类的add方法,该方法对Interval一无所知。

+0

谢谢!它现在通过radd方法工作! –

+0

不客气。 –