[Tutor] dictionary dispatch for object instance attributes question

Liam Clarke cyresse at gmail.com
Sun Feb 20 22:54:05 CET 2005


Ah, see, I should convince my bosses that I need a Python interpreter.
Of course, then they'd ask what Python was, and why I was thinking
about it at work....

Duh, I was just reading the docs, and I kept thinking that an
attribute was just a class variable.

Thanks, Kent, now I have all sorts of interesting experiments to undertake...


On Sun, 20 Feb 2005 07:26:54 -0500, Kent Johnson <kent37 at tds.net> wrote:
> Liam Clarke wrote:
> > Hi,
> >
> > just an expansion on Brian's query, is there a variant of getattr for
> > instance methods?
> >
> > i.e. class DBRequest:
> >     def __init__(self, fields, action):
> >         self.get(fields)
> >
> >     def get(self, fields):
> >         print fields
> >
> >
> > Instead of self.get in _init__, the value of action to call a
> > function? Or, is it going to have to be dictionary dispatch?
> 
> I don't understand your example, but instance methods are attributes too, so getattr() works with
> them as well as simple values.
> 
> An instance method is an attribute of the class whose value is a function. When you access the
> attribute on an instance you get something called a 'bound method' which holds a reference to the
> actual function and a reference to the instance (to pass to the function as the 'self' parameter).
> You can call a bound method just like any other function. So:
> 
>   >>> class foo:
>   ...   def __init__(self):
>   ...     self.bar = 3
>   ...   def baz(self):
>   ...     print self.bar
>   ...
>   >>> f=foo()
> 
> getattr() of a simple attribute:
>   >>> getattr(f, 'bar')
> 3
> 
> getattr() of an instance method returns a 'bound method':
>   >>> getattr(f, 'baz')
> <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>>
> 
> Calling the bound method (note the added ()) is the same as calling the instance method directly:
>   >>> getattr(f, 'baz')()
> 3
> 
> Of course you can do the same thing with dot notation for attributes:
>   >>> b=f.baz
>   >>> b
> <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>>
>   >>> b()
> 3
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list