keyerror '__repr__'

V

vijay shanker

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]
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.
 
C

Chris Rebert

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]
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).... def __str__(self): return "bar"
.... def __repr__(self): return "qux"
....See http://docs.python.org/reference/datamodel.html#object.__repr__


Cheers,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top