example from the book

Q

questions?

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
 
P

Paul McGuire

questions? said:
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
 

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,776
Messages
2,569,603
Members
45,197
Latest member
ScottChare

Latest Threads

Top