"Shrutarshi Basu" <technorapt...@gmail.com> wrote
I have a list containing strings like :
func1[]
func2[1,2]
func3[blah]
I want to turn them into method calls (with numeric or string
arguments) on a supplied object.
The easiest way is to call getattr() which will return a reference
to the method if it exists.
be rather complex (mainly graphics manipulation) I would like to
start
by getting a list of the object's methods and make sure that all the
strings are valid.
Why not just handle it using try/except?
Thats exactly what exceptions were designed for.
Is there a way to ask an object for a list of it's
methods (with argument requirements if possible)?
You can try dir() but that won't give you the parameters.
But again try/except can catch an invalid call and you can detect
whether the number of parameters is wrong in the except clause.
method name (say func1) in a variable, say var, could I do
object.var() and have if call the func1 method in object?
no, but you can do this:
class C:
... def f(self, x): print x
...
c = C()
dir(c)
['__doc__', '__module__', 'f']
m = getattr(c,'f')
m(42)
42
try: m(43,'foo')
... except TypeError:
... # parse the error message here
... print 'Method of', c, 'takes ??? arguments'
...
Method of <__main__.C instance at 0x01BF8350> takes ??? arguments
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor