[Tutor] class.__repr__: 'str' object is not callable???

Don Arnold Don Arnold" <darnold02@sprynet.com
Thu May 1 06:45:03 2003


----- Original Message -----
From: <pan@uchicago.edu>
To: <tutor@python.org>
Sent: Wednesday, April 30, 2003 10:37 PM
Subject: [Tutor] class.__repr__: 'str' object is not callable???


> Can someone tell me what the hell is happening in the
> following code?
>
> Why __getattr__ gets called when the __repr__ is the actual
> one that I called?
>
> Why is the ['str' object is not callable] happen ??
>
> thx in advance.
>
> pan
>
>
> >>> class aClass:
> ..     def __init__(self):pass
> ..     def __repr__(self):
> ..        return 'this is aClass'
> ..     def __getattr__(self, name):
> ..        print 'getting attr'       #<==== [A]
> ..        return 'returned value'
> ..
> >>>
> >>> a=aClass()
> >>> a
> this is aClass
>
> >>> print a
>  getting attr
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: 'str' object is not callable
> >>>
>

Although __repr__ and __str__ often return the same results, __str__ is what
get's called when you try to print the object. Since you've overridden
__getattr__, the lookup for the object's __str__ method returns the string
'returned value', which isn't callable.

HTH,
Don