On 29 September 2012 21:15, Albert-Jan Roskam <fo...@yahoo.com> wrote:
> Hi, > > 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? No. > I'd find it useful is this is standard behavior of Python. Or am I > overlooking something? > Yes. > > > 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, ") > else: > code += ("%(" + arg + ")s, ") > code = code[:-2] + ")" > return code % self.__dict__ > > x = X() > eval(repr(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): Oscar
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor