I want to overload my string method, s.t. I get the following output:
print Class_name({6:7, 4:5, 7:7})
7*x^7 + 7*x^6 + 5*x^4
I did the following:
def __str__(self):
self.poly = []
for k,v in sorted(self.dictionary.iteritems()):
if k == 0:
self.poly.append(str(v))
elif v == 1:
self.poly.append('*x^'+str(k))
else:
self.poly.append(str(v)+'*x^'+str(k))
out = ""
for el in self.poly:
out += str(el) + " + "
self.out = out[:-2]
return self.out
Why does this not work?
Entering
print Class_name({6:7, 4:5, 7:7})
, I get
{4: 13, 6: 14, 7: 7}
Thanks for any help!
Edit: If I've an additional def:
def __add__(self, other):
out = self.dictionary
for k,v in sorted(other.dictionary.iteritems(), reverse=True):
try:
out[k] += v
except:
out[k] = v
return out
and I want to do this:
print Class_name({6:7, 4:5, 7:7})+Class_name({6:7, 4:5, 7:7})
I get:
{6:14, 4:10, 7:14}
instead of the desired representation.