Custom __str__ and __repr__ are not working
python
Solution
You seem to think that using `str(hop)` in the `TorCircuit.decrypt()` class translates to `self.__str__(hop)`. This is not the case. It translates to `hop.__str__()` instead.
In other words, don't put these methods on the `TorCircuit` class, put them on the `TorHop` class instead.
When you do add them to `TorHop`, take into account that `__str__` and `__repr__` do not take arguments. Remove the `hop` argument; `self` is the `TorHop` instance:
def __str__(self):
return 'hop #%d' % self.hop
def __repr__(self):
return 'hop #%d' % self.hop
I'd keep the `__repr__` to something a little more useful for debugging:
def __repr__(self):
return '<TorHop(%d)>' % self.hop
perhaps.
Next, you appear to expect the hops to be numbered. They are not. You can alter your loop to add a number before the value printed for the `TorHop` object, using the `enumerate()` function:
for i, hop in enumerate(self.hops):
print "decrypt: hop #{} {}".format(i, hop)
This will print `decrypt: hop #0`, then `decrypt: hop #1`, etc., followed by the result of `hop.__str__()`.
Problem
I am trying to convert an output such as : ``` decrypt : <torfuncs.TorHop instance at 0x7f44babb8440> ``` into something a bit more readable, the result should be a string from array. I have defined `__str__` and `__repr__` but even with these I am still getting the result above. What am I doing wrong? ``` class TorCircuit(): def __init__(self, sock, circid): self.hops = [] self.circId = circid self.socket = sock self.tempX = 0 self.packetSendCount = 0 self.cookie = [] def __str__(self, hop): return 'hop #%d' % self.hops def __repr__(self, hop): return 'hop #%d' % self.hops def decrypt(self, relayCell): for hop in self.hops: print "decrypt :", str(hop) relayCell = hop.decrypt(relayCell) if relayCell[1]==0 and relayCell[2]==0: return relayCell return relayCell ``` What I am trying to print out is the hop currently in use for the decryption edit TorHop ``` class TorHop: def __str__(self): return 'hop #' % self.hop def __repr__(self): return 'hop #' % self.hop def __init__(self, KH, Df, Db, Kf, Kb): self.KH = KH self.Df = Df self.Db = Db self.Kf = Kf self.Kb = Kb self.fwdSha = SHA.new() self.fwdSha.update(Df) self.bwdSha = SHA.new() self.bwdSha.update(Db) ctr = Counter.new(128,initial_value=0) self.fwdCipher = AES.new(Kf, AES.MODE_CTR, counter=ctr) ctr = Counter.new(128,initial_value=0) self.bwdCipher = AES.new(Kb, AES.MODE_CTR, counter=ctr) def encrypt(self, data): return self.fwdCipher.encrypt(data) def decrypt(self, data): return self.bwdCipher.decrypt(data) ``` with this I now get: ``` AttributeError: TorHop instance has no attribute 'hops' ```