Good or bad use of __repr__?
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Wed Feb 4 00:18:29 EST 2009
On Tue, 03 Feb 2009 22:02:13 -0600, Alaric Haag wrote:
> Hello,
>
> Is the use of __repr__ below a "really bad idea"?
>
> class Dimension():
> def __init__(self, setp, name):
> ptr = setp.contents.dim
> while ptr.contents.name != name:
> ptr = ptr.contents.next
> self.name = ptr.contents.name
> self.size = ptr.contents.size
> self.unlimited = bool(ptr.contents.unlimited)
> self.coord = ptr.contents.coord
> def __repr__(self):
> return '%g' % (self.size)
As a rule of thumb, you should aim for:
eval( repr(obj) )
to recreate the obj. That's not always possible, but when possible, it is
an ideal to aspire to. Given that, I'd recommend:
def __repr__(self):
return '%s(%s, %s)' % (
self.__class__.__name__, self.ptr, self.name)
def __str__(self):
return "<dim=%g>" % self.size
except of course your class doesn't store ptr.
But looking at the code shown, I'm guessing you have bigger design
problems than just what __repr__ should look like. I suggest you read
this:
http://www.surfscranton.com/architecture/LawOfDemeter.htm
--
Steven
More information about the Python-list
mailing list