Python - 来自二进制输出的字符串格式的TypeError

时间:2013-06-02 23:48:29

标签: python methods python-2.7 types

我得到一个未绑定方法的TypeError(在底部)。我正在自学Python,所以这可能是一个简单的错误。问题出在outFormat()上,当我自己测试它但没有在类中工作时,它没有给我带来问题。这是班级:

class gf2poly:
    #binary arithemtic on polynomials
    def __init__(self,expr):
        self.expr = expr
    def id(self):
        return [self.expr[i]%2 for i in range(len(self.expr))]
    def listToInt(self):
        result = gf2poly.id(self)
        return int(''.join(map(str,result)))
    def prepBinary(a,b):
        a = gf2poly.listToInt(a); b = gf2poly.listToInt(b)
        bina = int(str(a),2); binb = int(str(b),2)
        a = min(bina,binb); b = max(bina,binb);
        return a,b
    def outFormat(raw):
        raw = str(raw); g = []
        [g.append(i) for i,c in enumerate(raw) if c == '1']
        processed = "x**"+' + x**'.join(map(str, g[::-1]))
        #print "processed  ",processed
        return processed
    def divide(a,b): #a,b are lists like (1,0,1,0,0,1,....)
        a,b = gf2poly.prepBinary(a,b)
        bitsa = "{0:b}".format(a); bitsb = "{0:b}".format(b)
        difflen = len(str(bitsb)) - len(str(bitsa))
        c = a<<difflen; q=0
        while difflen >= 0 and b != 0:
            q+=1<<difflen; b = b^c
            lendif = abs(len(str(bin(b))) - len(str(bin(c))))
            c = c>>lendif; difflen -= lendif
        r = "{0:b}".format(b); q = "{0:b}".format(q)
        #print "r,q  ",type(r),type(q)
        return r,q #returns r remainder and q quotient in gf2 division
    def remainder(a,b): #separate function for clarity when calling
        r = gf2poly.divide(a,b)[0]; r = int(str(r),2)
        return "{0:b}".format(r)
    def quotient(a,b): #separate function for clarity when calling
        q = gf2poly.divide(a,b)[1]; q = int(str(q),2)
        return "{0:b}".format(q)

这就是我的称呼方式:

testp = gf2poly.quotient(f4,f2)
testr = gf2poly.remainder(f4,f2)
print "quotient: ",testp
print "remainder: ",testr
print "***********************************"    
print "types  ",type(testp),type(testr),testp,testr
testp = str(testp)
print "outFormat testp: ",gf2poly.outFormat(testp)
#print "outFormat testr: ",gf2poly.outFormat(testr)

这是错误:

TypeError: unbound method outFormat() must be called with gf2poly instance as first argument (got str instance instead)

1 个答案:

答案 0 :(得分:1)

你有这个:

def outFormat(raw):

你可能想要这个:

def outFormat(self, raw):

或者这个:

@staticmethod
def outFormat(raw):

前者如果您最终需要访问self中的outFormat(),或者如果您不需要访问后者(如发布代码中的情况那样)。