example from the book
Paul McGuire
ptmcg at austin.rr._bogus_.com
Wed Jan 17 23:19:14 EST 2007
"questions?" <universal_used at hotmail.com> wrote in message
news:1169087861.453278.58680 at a75g2000cwd.googlegroups.com...
>I am a little confused by an example in python book:
>
> class wrapper:
> def __init__(self,object):
> self.wrapped=object
> def __getattr__(self,attrname):
> print "Trace:",attrname (<<<===)
> print getattr(self.wrapped,attrname) (*)
> return getattr(self.wrapped,attrname) (**)
>
> x=wrapper({"a":1, "b":2})
> print x.keys() (**)
>
>
> (*) will output: <built-in method keys of dict object at 0xb7f0f4f4>
> while two (**) statements together will print the keys of the
> dictionary which is ['a','b']
>
> why (*) doen't output the same result as (**)?
>
> Thanks
Because the line (*) prints out the reference to a method, and the second
line labeled (**) calls that method and prints that method's return value.
As a hint, what does the line marked by (<<<===) print? I'm guessing it
printed the attribute name 'keys'. __getattr__ didn't return the dict's
keys, it returned the dict's "keys" method, which the calling code then
invoked with ()'s, which invoked the wrapped object's "keys" method, which
returned the wrapped object's keys, 'a' and 'b'.
-- Paul
More information about the Python-list
mailing list