__str__ not working as expected?

I am making a class that records a result from an named query interaction with the database. I am trying to make it print nicely so I can log it and it looks nice. My code is

class Response(object):
	# TODO Figure out if these should remain keywords or shold just be positional argsProbably should not be keywords b
    def __init__(self, success=False, result=None, error=None, errorType=None):
        self.success = success
        self.result = result
        self.error = error
        self.errorType = errorType

	def __str__(self):
		if self.success:
			return "Success: True, Result: %s"%(str(self.result))
		else:
			return "Error Type %s Error Text: %s"%(self.errorType, self.error)

	def __repr__(self):
		if self.success:
			return "Success: True, Result: %s"%(str(self.result))
		else:
			return "Error Type %s Error Text: %s"%(self.errorType, self.error)

However, doing

r = forms2.common.Response(success=True, result='Hi!', error=None, errorType=None)
print str(r)

prints <common.Response object at 0x3>. Not sure what I am missing here. When __str__ was not doing the trick I though maybe I needed __repr__ but I thought __repr__ is more for printing out the configuration of the class/all the attributes that it was initialized too for recreation purposes. What am I doing wrong?

Your indentations don't match. 4 spaces in front of __init__ indentations vs tabs everywhere else.

class Response(object):
	# TODO Figure out if these should remain keywords or shold just be positional argsProbably should not be keywords b
	def __init__(self, success=False, result=None, error=None, errorType=None):
		self.success = success
		self.result = result
		self.error = error
		self.errorType = errorType

	def __repr__(self):
		if self.success:
			return "Success: True, Result: %s"%(str(self.result))
		else:
			return "Error Type %s Error Text: %s"%(self.errorType, self.error)

r = Response(success=True, result='Hi!', error=None, errorType=None)

print r
print str(r)
str(r)
r

Output

Success: True, Result: Hi!
Success: True, Result: Hi!
'Success: True, Result: Hi!'
Success: True, Result: Hi!
1 Like

Wow I don't know how that happened but also puzzled it ever worked? I thought mismatch of spaces and tabs usually threw an IndentationError. Guess not necessarily true when it occurs inside of a class.

Thanks!

1 Like

It hit up the __init__ okay, but __str__ and __repr__ used the defaults, since the indentation didn't match. I finally figured it out when I tried to add a new method to it.

1 Like

I guess OpenAI does not know about the importance of tabs vs spaces in python! I had it mock this up for me and I just added a few extra fields in the __init__.

2 Likes