0
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'
4

1 回答 1

0

这是因为x是一个str(字符串)。

那是因为你从你的__add__函数中返回了一个字符串,以及__mul__,但显然假设它是一个Natural. 您应该更改这些函数以返回 a Natural

于 2013-05-04T03:13:32.780 回答