Need help understanding list structure
MRAB
python at mrabarnett.plus.com
Tue May 3 15:57:12 EDT 2016
On 2016-05-03 18:54, Dan Strohl via Python-list wrote:
>
>> I added a __repr__ method at the end of the gedcom library like so:
>>
>> def __repr__(self):
>> """ Format this element as its original string """
>> result = repr(self.level())
>> if self.pointer() != "":
>> result += ' ' + self.pointer()
>> result += ' ' + self.tag()
>> if self.value() != "":
>> result += ' ' + self.value()
>> return result
>>
>> and now I can print myList properly.
>>
>> Eric and Michael also mentioned repr above, but I guess I needed someone
>> to spell it out for me. Thanks for taking the time to put it in terms an old dog
>> could understand.
>>
>
> Glad to help! (being an old dog myself, I know the feeling!)
>
> One other point for you, if your "__repr__(self)" code is the same as the "__str__(self)" code (which it looks like it is, at a glance at least), you can instead reference the __str__ method and save having a duplicate code block... some examples:
>
> =========
> Option 1: This is the easiest to read (IMHO) and allows for the possibility that str() is doing something here like formatting or whatever. (in this case it shouldn't be though). However, to call this actually is taking multiple steps (calling object.__repr__, whch calls str(), which calls object.__str__(). )
>
> def __repr__(self):
> return str(self)
>
> =========
> Option 2: this isn't hard to read, and just takes two steps (calling object.__repr__(), which calls object.__str__().
>
> def __repr__(self):
> return self.__str__()
>
> ========
> Option 3: it's not that this is hard to read, but since it doesn't follow the standard "def blah(self):" pattern, sometimes I overlook these in the code (even when I put them there). This however is the shortest since it really just tells the object to return object.__str__() if either object.__repr__() OR object.__str__() is called.
>
>
> __repr__ = __str__
>
>
> This probably doesn't matter much in this case, since it probably isn't called that much in normal use (though there are always exceptions), and in the end, Python is fast enough that unless you really need to slice off a few milliseconds, you will never notice the difference, but just some food for thought.
>
>
Option 4:
Delete the __str__ method.
If there's no __str__, Python falls back to __repr__.
If there's no __repr__, Python falls back to the <Something object at
somewhere> format.
More information about the Python-list
mailing list