has_method (solution found)

Eric Brunel eric_brunel at despammed.com
Tue Aug 31 09:50:47 EDT 2004


Gandalf wrote:
> 
> Somebody sent me a private e-mail.
> It must be common for such silly questions that would just spam the 
> list. :-)
> I'll write down the final solution anyway.
> 
> 
> def getmethod(name):
>    methodList = [e for e in dir(self) if callable(getattr(self, e))]
>    if name in methodList:
>       return getattr(self,name)
>    else:
>       return None

And why not:

def getmethod(obj, name):
   meth = getattr(obj, name)
   if callable(meth):
     return meth
   else:
     return None

???

Why do you use a list comprehension to get the names of all methods on the object?
In addition, it won't work for class instances:

 >>> class C:
...   def m(self):
...     print 'spam'
...
 >>>
 >>> o = C()
 >>> dir(o)
[]

But:

 >>> getattr(o, 'm')
<method C.m of C instance at 0x821433c>

HTH
-- 
- Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com




More information about the Python-list mailing list