[Tutor] new classes and default attribute

Lloyd Kvam pythontutor at venix.com
Wed Nov 19 10:24:40 EST 2003


Gonçalo Rodrigues wrote:

> On Wed, 19 Nov 2003 00:20:15 -0500, you wrote:
> 
> 
>>An instance of the builtin types will return its value when referenced.
>>
>>>>>class I(int):
>>
>>... 	pass
>>...
>>
>>>>>i = I(123)
>>>>>i
>>
>>123
>>
>>An instance of a "normally" defined class returns type information.
>>
>>>>>class O(object):
>>
>>... 	pass
>>...
>>
>>>>>o = O(123)
>>>>>o
>>
>><__main__.O object at 0x016F0420>
>>
>>Where does this difference in behavior come from?  Is there a __????__
>>that can be used when defining a class to get similar behavior?
> 
> 
> Look up the __repr__ and __str__ methods. In the above __repr__ is
> used, e.g.
> 
> 
>>>>class Test(object):
> 
> ... 	def __repr__(self):
> ... 		return "This is a test."
> ... 	
> 
>>>>a = Test()
>>>>a
> 
> This is a test.

That is true for a string, but doesn't work with a number.

 >>> repr(i)
'123'
 >>> i.__repr__()
'123'
 >>> i
123

I did try to look this up, but none of the "magic methods" seemed to apply.
I do agree that __repr__ comes close.

> 
> 
> With my best regards,
> G. Rodrigues
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list