python 3.x - How do I make it possible to subtract and multiply in both directions in a class method -
so trying program can add, subtract , multiply volumes (which consist of magnitude , unit) got __add__ work __rsub__ , __mult__ have not figured out how make them work. want able operations volume * 2 or 2 * volume. advice on how go appreciated!
def __add__ (self, v2): #adds magnitude using int or volume if volume.is_valid(self): if isinstance(v2, volume): if volume.is_valid(v2): #check if v2 valid if self.__units == v2.__units: return volume(self.__magnitude + v2.__magnitude, self.__units) else: if v2.__units == 'ml': v3 = v2.customary() return volume(self.__magnitude + v3.__magnitude, self.__units) elif v2.__units == 'oz': v3 = v2.__units return volume(self.__magnitude + v3.__magnitude, self.__units) elif isinstance(v2,(int,float)): #create new volume same units self v3 = volume(v2, self.__units) return volume(self.__magnitude + v3.__magnitude, self.__units) def __radd__ (self, v2): #adds ability i.e. 2 + return self.__add__(v2) def __sub__ (self, v2): #same __add__ subtracts if volume.is_valid(self): if isinstance(v2, volume): if volume.is_valid(v2): if self.__units == v2.__units: return volume(self.__magnitude - v2.__magnitude, self.__units) else: if v2.__units == 'ml': v3 = v2.customary() return volume(self.__magnitude - v3.__magnitude, self.__units) elif v2.__units == 'oz': v3 = v2.__units return volume(self.__magnitude - v3.__magnitude, self.__units) elif isinstance(v2,(int,float)): v3 = volume(v2, self.__units) return volume(self.__magnitude - v3.__magnitude, self.__units) def __rsub__ (self, v2): return volume(v2.__magnitude - self.__magnitude, self.__units) def __mult__ (self, v2):#multiplies volume int (not other vol) if volume.is_valid(self): if isinstance(v2, volume): if volume.is_valid(v2): if self.__units == v2.__units: return volume(self.__magnitude * v2.__magnitude, self.__units) else: if v2.__units == 'ml': v3 = v2.customary() return volume(self.__magnitude * v3.__magnitude, self.__units) elif v2.__units == 'oz': v3 = v2.__units return volume(self.__magnitude * v3.__magnitude, self.__units) elif isinstance(v2,(int,float)): v3 = volume(v2, self.__units) return volume(self.__magnitude * v3.__magnitude, self.__units) #return volume(self.__magnitude * v2, self.__units) def __rmult__ (self, v2): return self.__mult__(v2)
the magic method multiplying __mul__, not __mult__.
__rsub__ doesn't appear work __sub__. perhaps like:
def __rsub__(self, v2): return volume(v2) - self would better.
Comments
Post a Comment