Python - multiplication between a variable that belong to the same class -
how set class variable return other data type (list or int)?
so have 2 variable belong same class , want use operator example multiplication both of variables, cannot done because both of them have class data type.
for example:
class multip: def __init__(self,x,y): self.x = x self.y = y def __repr__(self): return "{} x {}".format(self.x, self.y) def __str__(self): return "{}".format(self.x*self.y) def __mul__(self, other): thisclass = self.x*self.y otherclass = other return thisclass * otherclass = multip(5,6) b = multip(7,5) c = a*b print(c)
this return error:
typeerror traceback (most recent call last) in () 14 = multip(5,6) 15 b = multip(7,5) ---> 16 c = a*b 17 print(c)
in mul(self, other) 10 thisclass = self.x*self.y 11 otherclass = other ---> 12 return thisclass * otherclass 13 14 = multip(5,6)
typeerror: unsupported operand type(s) *: 'int' , 'multip'
to work, this:
otherclass = other.x*other.y
instead of
otherclass = other
this mean otherclass int , multiplication work.
Comments
Post a Comment