class Natural:
def __init__(self,x):
self.n=str(x)
def __add__(self,x):
i=1
suma=""
a=0
if len(self.n)==len(x.n):
l=len(self.n)
elif len(self.n)>len(x.n):
l=len(self.n)
elif len(self.n)<len(x.n):
l=len(x.n)
if len(self.n)>len(x.n):
while True:
x.n="0"+x.n
if len(self.n)==len(x.n):break
elif len(self.n)<len(x.n):
while True:
self.n="0"+self.n
if len(self.n)==len(x.n):break
while i<=l:
s=(int(self.n[l-i])+int(x.n[l-i])+a)
u=s%10
suma=str(u)+suma
a=s/10
i=i+1
if a==0:
return suma
elif a==1:
return str(a)+suma
def __mul__(self,x):
i=1
if len(self.n)==len(x.n):
c=int(self.n)
elif len(self.n)>len(x.n):
c=int(x.n)
elif len(self.n)<len(x.n):
c=int(self.n)
if len(self.n)>len(x.n):
s=Natural(self.n)
mult=""
while i<=c:
mult=s+mult
i=i+1
return mult
elif len(self.n)<len(x.n):
s=Natural(x.n)
mult=""
while i<=c:
mult=s+mult
i=i+1
return mult
def __gt__(self,x):
return self.n>x.n
def __lt__(self,x):
return self.n<x.n
def __eq__(self,x):
return self.n==x.n
def __str__(self):
return str(self.n)
def __len__(self):
return len(self.n)
当我尝试使用递归加法进行 mult 时,出现此错误:
Traceback (most recent call last):
File "C:\Python27\Natural.py", line 82, in <module>
print "X*Y="+str(Natural(x)*Natural(y))
File "C:\Python27\Natural.py", line 54, in __mul__
mult=s+mult
File "C:\Python27\Natural.py", line 10, in __add__
if len(self.n)==len(x.n):
AttributeError: 'str' object has no attribute 'n'