class - use python to add two custom datatypes? -
class myint(object) : # i'm trying add 2 custom types (myint) # , have sum same type. (myint) # doing wrong? def __init__(self, x): self.x = x def __add__(self,other): return self.x + other = myint(1) b = myint(1) print + 1 # ----> 2 print type(a) # ----> "class '__main__.myint' #c = + b # won't work #print + b # won't work
there error in __add__, should be:
def __add__(self,other): return myint(self.x + other.x) then, can add myint instances:
a = myint(1) b = myint(1) c = + b print type(c) # prints <class '__main__.myint'> print c.x # prints 2 note, a + 1 won't work since 1 not type of myint. if want support it, you'll need improve __add__ method , define how behave in case of different types of other argument.
Comments
Post a Comment