AttributeError:'str'对象在第10行没有属性'n'

时间:2013-05-03 23:18:15

标签: class python-2.7 attributeerror

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)

当我尝试使用递归添加进行多重播放时,我收到此错误:

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'

1 个答案:

答案 0 :(得分:0)

这是因为xstr(字符串)。

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