Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

keyerror '__repr__'

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


vshanker.88 at gmail

Aug 4, 2012, 7:48 AM

Post #1 of 2 (104 views)
Permalink
keyerror '__repr__'

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.
--
http://mail.python.org/mailman/listinfo/python-list


clp2 at rebertia

Aug 4, 2012, 8:31 AM

Post #2 of 2 (104 views)
Permalink
Re: keyerror '__repr__' [In reply to]

On Sat, Aug 4, 2012 at 7:48 AM, vijay shanker <vshanker.88 [at] gmail> 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
--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.