# 关于自定义类的函数返回值的疑问

150 次浏览

a=P([1,2,3])
b=P([2])
a+b

a+b
a+b

### 相关代码

class P():

def __init__(self,p):
self.p = p
self.n = len(self.p)
self.f = []
self.s = []
for i in range(self.n):
self.f.append([self.p[i],self.n - (i+1)])

def __str__(self):
for i in range(self.n):
if self.n - i > 2:
if self.f[i][0] != 0:
self.s.append(str(self.f[i][0]) + " x**" +
str(self.f[i][1]))
if self.n - i == 2:
if self.f[i][0] != 0:
self.s.append(str(self.f[i][0]) + " x")
if self.n - i == 1:
self.s.append(str(self.f[i][0]))
self.S = '+'.join(self.s)
return str(self.S)
__repr__=__str__

def add(self,addp):
if self.n >= addp.n:
self.min = addp
self.max = self
else:
self.max = addp
self.min = self
self.addp = self.max.p
for i in range(1,self.min.n+1):
self.addp[-i] = self.addp[-i] + self.min.p[-i]
self.addpp = P(self.addp)
return self.addpp
def __add__(self,P):
return self.add(P)

def mul(self,mulp):
self.min = P([0])
self.max = P([0])
self.multemp2 = []
self.multemp0 = P([0])
if self.n >= mulp.n:
self.min = mulp
self.max = self
else:
self.max = mulp
self.min = self
self.max.p = self.max.p[::-1]
self.min.p = self.min.p[::-1]
for i,j in zip(range(len(self.min.p)), self.min.p):
self.multemp1 = []
while i > 0:
self.multemp1.append(0)
i -= 1
for k in self.max.p:
self.multemp1.append(j*k)
self.multemp2 = self.multemp1[::-1]
self.multemp0 = self.multemp0.add(P(self.multemp2))
return self.multemp0
def __mul__(self,P):
return self.mul(P)

2019-06-15 提问
1 个回答