我想重载我的字符串方法,s.t。我得到以下输出:
print Class_name({6:7, 4:5, 7:7})
7*x^7 + 7*x^6 + 5*x^4
我做了以下事情:
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
为什么这不起作用?
进入
print Class_name({6:7, 4:5, 7:7})
,我得到
{4: 13, 6: 14, 7: 7}
感谢您的帮助!
编辑: 如果我有一个额外的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
我想这样做:
print Class_name({6:7, 4:5, 7:7})+Class_name({6:7, 4:5, 7:7})
我得到:
{6:14, 4:10, 7:14}
代替所需的代表。
答案 0 :(得分:1)
这对我有用(从代码中剪切并粘贴,包含在类定义中)
class cn:
def __init__(self, d):
self.dictionary = d
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
print cn({"1":"2"})
~ mgregory$ python foo.py
2*x^1
~ mgregory$ python --version
Python 2.7.5
~ mgregory$
我想知道你是否真的没有定义你班级的__str__()
- 也许你刚刚定义了一个名为__str__()
的函数......
答案 1 :(得分:1)
为了加入工作:
def __add__(self, other):
#...
return Class_name(out)
答案 2 :(得分:0)
您需要为班级
定义__repr__
函数
class Poly():
def __init__(self, coeffs):
values = [(factor, power) for power, factor in coeffs.items()]
self.poly = sorted(values, reverse = True)
def __repr__(self):
return ' + '.join('{}*x^{}'.format(f, p) for f, p in self.poly)
实施例
>>> a = Poly({6:7, 4:5, 7:7})
>>> a
7*x^7 + 7*x^6 + 5*x^4
>>> print(a)
7*x^7 + 7*x^6 + 5*x^4
>>> str(a)
'7*x^7 + 7*x^6 + 5*x^4'