[Tutor] generic repr method?
Albert-Jan Roskam
fomcl at yahoo.com
Sat Sep 29 22:15:29 CEST 2012
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? 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):
code += ("%(" + arg + ")r, ")
else:
code += ("%(" + arg + ")s, ")
code = code[:-2] + ")"
return code % self.__dict__
x = X()
eval(repr(x))
Regards,
Albert-Jan
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the Tutor
mailing list