[Tutor] generic repr method?
Albert-Jan Roskam
fomcl at yahoo.com
Mon Oct 1 14:16:58 CEST 2012
----- Original Message -----
> From: eryksun <eryksun at gmail.com>
> To: Albert-Jan Roskam <fomcl at yahoo.com>
> Cc: Python Mailing List <tutor at python.org>
> Sent: Sunday, September 30, 2012 1:46 AM
> Subject: Re: [Tutor] generic repr method?
>
> On Sat, Sep 29, 2012 at 4:15 PM, Albert-Jan Roskam <fomcl at yahoo.com>
> wrote:
>>
>> 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__
>
>
> __init__ could use *args and **kwds.
> Keyword-only arguments in Python 3 require using inspect.getfullargspec.
> A class with __slots__ probably lacks a __dict__.
> Use the repr of all values.
Hi Oscar, Eryksun,
Thanks! My code was an attempt to generalize a __repr__ method from Mark Summerfield's book (http://www.amazon.com/Programming-Python-Complete-Introduction-Language/dp/0137129297). But the inability to deal with *args, **kwargs is maybe its biggest shortcoming. And, as Oscar noted, it depends on the convention that somevalue always maps to self.somevalue in __init__. I had not considered __slots__ at all. I have read about it; IIRC they can be uised to "slim down" a class so it uses less memory. Is it true that this is not used very often?
It seems that for my current project I could still use the code, though I'd find it more readable if the keywords are also included in the string.
Thanks again!
Albert-Jan
<snip>
More information about the Tutor
mailing list