Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

keyerror '__repr__'

20 views
Skip to first unread message

vijay shanker

unread,
Aug 4, 2012, 10:48:07 AM8/4/12
to
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.

Chris Rebert

unread,
Aug 4, 2012, 11:31:34 AM8/4/12
to vijay shanker, pytho...@python.org
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
0 new messages