keyerror '__repr__'

Chris Rebert clp2 at rebertia.com
Sat Aug 4 17:31:34 CEST 2012


On Sat, Aug 4, 2012 at 7:48 AM, vijay shanker <vshanker.88 at gmail.com> wrote:
> hi
> i have this class book
>
> class book:
>     def __init__(self,name,price):
>         self.name = name
>         self.price = price
>
>     def __getattr__(self,attr):
>         if attr == '__str__':
>             print 'intercepting in-built method call '
>             return '%s:%s' %
> (object.__getattribute__(self,'name'),object.__getattribute___(self,'price'))
>         else:
>             return self.__dict__[attr]
>
>>>>b = book('the tempest',234)
>>>>b
> Traceback (most recent call last):
>   File "<console>", line 1, in <module>
>   File "<console>", line 11, in __getattr__
> KeyError: '__repr__'
>
> i am missing on a concept here. please enlighten me.

A. You ought to be subclassing the `object` class so that your class
is new-style (see
http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes
); "classic" classes are deprecated. Incidentally, you can't intercept
special method lookups on new-style classes like you do in your code
snippet (see http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes
). You'll need to define actual __repr__() and/or __str__() methods.

B. The interactive interpreter uses repr(), rather than str(), to
stringify results.
$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
>>> class Foo(object):
...     def __str__(self): return "bar"
...     def __repr__(self): return "qux"
...
>>> Foo()
qux
>>>
See http://docs.python.org/reference/datamodel.html#object.__repr__


Cheers,
Chris
--
http://rebertia.com


More information about the Python-list mailing list