[Python-il] Printing dictionary values rather than references [SOLVED]

Amit Dor-Shifer amitds at oversi.com
Thu Jun 11 10:08:27 IDT 2009


Thanks Shai (and others). Indeed replacing the __str__ override with
__repr__ did the trick :)

my python version:
amit0 src # python -V
Python 2.5.4

Amit


Shai Berger wrote:
> 0. There is no way to 'print references' in python (that I'm aware of). The 
> question is: "Why is my object transformed to a string using the default 
> method rather than my __str__?"
>
> 1. Is this Python 2 or 3?
>
> 2. In my python 2.6, you can get what you want be defining __repr__ instead of 
> __str__.
>
> Hope this helps,
> 	Shai.
>
> On Wednesday 10 June 2009 17:28:20 Amit Dor-Shifer wrote:
>   
>> Hi all.
>>
>> I'd like to print-out a dictionary of objects. The printed values are
>> references. How Do I print the actual objects.
>>
>> class MyClass:
>>     def __str__(self):
>>         return str(self.__dict__)
>>
>> if __name__ == '__main__':
>>     dict = dict()
>>     classA = MyClass()
>>     setattr(classA, "attr-1", "val-1")
>>
>>     dict['a']= classA
>>     print classA
>>     ''' Desired output: {'attr-1': 'val-1'}'''
>>     print dict
>>     ''' Actual output: {'a': <__main__.MyClass instance at 0x79cfc8>}'''
>>
>> Thanks,
>> Amit
>>
>> _______________________________________________
>> Python-il mailing list
>> Python-il at hamakor.org.il
>> http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
>>     
>
> _______________________________________________
> Python-il mailing list
> Python-il at hamakor.org.il
> http://hamakor.org.il/cgi-bin/mailman/listinfo/python-il
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://hamakor.org.il/pipermail/python-il/attachments/20090611/bf43def5/attachment.htm 


More information about the Python-il mailing list