dictionary with object's method as thier items

Bruno Desthuilliers onurb at xiludom.gro
Wed Aug 30 10:46:47 EDT 2006


noro wrote:
> Is it possible to do the following:
> 
> for a certain class:
> 
> ----------------------------
> class C:
> 
>     def func1(self):
>          pass
>     def func2(self):
>          pass
>     def func4(self):
>          pass
> 
> obj=C()
> ----------------------------
> 
> by some way create a dictionary that look somthing like that:
> 
> d= {'function one': <reference to C.func1()>, \
>       'function two': <reference to C.func2()>, \
>       'function three': <reference to C.func3()>}
> 
> and so i could access every method of instances of C, such as obj with
> sometiing like:
> (i know that this syntax wont work )
> 
> obj.(d['function one'])
> obj.(d['function two'])
> etc..
> 

Let me guess... What you want to is in fact to call a method by it's
name ? If so, getattr(obj, name) is your friend:

class Knight(object):
  def __init__(self):
    self._saywhat = "ni"
    self._wantwhat ="shrubbery"

  def says(self):
    return self._saywhat

  def wants(self):
    return self._wantwhat

k = Knight()

print getattr(k, "says")()
print getattr(k, "wants")()

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list