[Tutor] generic repr method?
oscar.j.benjamin at gmail.com
Sun Sep 30 01:16:48 CEST 2012
On 29 September 2012 21:15, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> I've written a __repr__ method that is supposed to *always* work. That is,
> it returns an eval-able text representation of any class instance.
> Will this really always work?
> I'd find it useful is this is standard behavior of Python. Or am I
> overlooking something?
> import inspect
> class X (object):
> def __init__(self, x=1, y='n'):
> self.x = x
> self.y = y
> def __repr__(self):
> code = self.__class__.__name__ + "("
> for arg in inspect.getargspec(self.__init__).args [1:] :
> if isinstance(eval("self." + arg), basestring):
I'd prefer getattr(self, arg) to eval("self." + arg).
> code += ("%(" + arg + ")r, ")
> code += ("%(" + arg + ")s, ")
> code = code[:-2] + ")"
> return code % self.__dict__
> x = X()
This repr method assumes that every argument to __init__ is stored as an
attribute with the same name as the parameter to __init__. Consider:
def __init__(self, name):
self.other_name = name
Also how do you handle:
def __init__(self, *args, **kwargs):
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor