Can print() be reloaded for a user defined class?

Dave Angel davea at ieee.org
Sun Sep 20 11:42:35 CEST 2009



Peng Yu wrote:
> <snip>
>>     def __str__(self):
>>         return 'Bin(%s, %s)' %(self.x, self.y)
>>     __repr__ =_str__
>>
>> Please use an initial capital letter when defining a class, this is
>> the accepted way in many languages!!!
>>     
>
> I want to understand the exact meaning of the last line ('__repr__ __str__'). Would you please point me to the section of the python
> manual that describes such usage.
>
> Regards,
> Peng
>
>   
I don't know where to look in the various manuals, but what we have here 
are class attributes.  Inside the class definition, each method 
definition is a class attribute.  In addition, any "variable" definition 
is a class attribute as well.  For example,
  class  MyClass(object):
        counter = 0
        def __str__(self):
              return "Kilroy"+str(self.value)
        def __init__(self, num):
              self.value = num+1

counter is a class attribute, initialized to zero.  That attribute is 
shared among all the instances, unlike data attributes, which are 
independently stored in each instance.

Anyway, the   __repr__ = __str__   simply copies a class attribute.  So 
now you have two names which call the same method.  To explicitly call 
one of them, you might use:


obj = MyClass(42)
mystring = obj.__str__()        #mystring is now "Kilroy43"


But normally, you don't directly call such methods, except for debug 
purposes.  They are implicitly called by functions like print().





More information about the Python-list mailing list