2013-06-02 79 views
0

我得到一個TypeError for unbound方法(在底部)。我自學Python,所以這可能是一個簡單的錯誤。這個問題與outFormat()有關,當我單獨測試它時,它並沒有給我帶來問題,但它不在課堂上工作。下面是類:Python - 從二進制輸出字符串格式的TypeError

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

我建議堅持約定,並使用'self'作爲方法的第一個參數(實例) –

回答

1

如果你有這樣的:

def outFormat(raw): 

你可能想要這個:

def outFormat(self, raw): 

或者這樣:

@staticmethod 
def outFormat(raw): 

前者,如果你最終需要在outFormat()訪問self,或者如果你不這樣做(如目前在發佈代碼的情況下)的後者。

+0

謝謝john!輝煌的答案。我會google的@staticmethod意味着什麼,爲什麼它需要在這裏,以便我不會在未來犯這樣的錯誤。 – stackuser