我需要有关此代码的帮助。当我在终端中运行它时,我得到:
<__main__.Polynomial instance at 0x2b6ae51c80e0>
<__main__.Polynomial instance at 0x2b6ae51c84d0>
Traceback (most recent call last):
File "Polynomial_dict1.py", line 36, in <module>
print p+p2
File "Polynomial_dict1.py", line 22, in __add__
result_d[key] = other.d[:]
TypeError: unhashable type
我不知道出了什么问题。这是代码:
from Polynomial import*
class Polynomial:
def __init__(self, dictionary):
self.d = dictionary
def __call__(self, x):
s = 0
for key in d.keys:
s += self.d[key]*x**key
return s
def __add__(self, other):
if len(self.d)>len(other.d):
result_d = self.d[:] # copy
for key in d.keys:
result_d[key] += other.get(key,0)
else:
result_d = other.d[:]
for key in d.keys:
result_d[key] += self.d.get[key,0]
return Polynomial(result_d)
p = Polynomial({1:1,100:-3})
p2 = Polynomial({1:-1,20:1,100:4})
print p
print p2
print p+p2