/ / Python - TypeError na formacie tekstowym z wyjścia binarnego - python, metody, python-2.7, typy

Python - TypeError na formacie tekstowym z wyjścia binarnego - python, metody, python-2.7, typy

Otrzymuję błąd TypeError dla niezwiązanegometoda (na dole). Uczę się Pythona, więc może to być zwykły błąd. Problem dotyczy OutFormat (), który nie przysporzył mi problemów, gdy testuję go sam, ale nie działa w klasie. Oto klasa:

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)

Tak to nazywam:

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)

To jest błąd:

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

Odpowiedzi:

1 dla odpowiedzi № 1

Gdzie masz to:

def outFormat(raw):

Prawdopodobnie chcesz tego:

def outFormat(self, raw):

Albo to:

@staticmethod
def outFormat(raw):

Ten pierwszy, jeśli w końcu potrzebujesz dostępu self w outFormat(), lub te drugie, jeśli tego nie robisz (tak jak ma to obecnie miejsce w opublikowanym kodzie).