Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> > Can someone suggest an efficient way of calling method whose name is
> > passed in a variable?
> >
>
> method = getattr(obj, 'method_name', None)
> if callable(method):
> method(args)
I think that that is needless LBYL...
getattr(obj, 'method_name')(args)
Will produce some perfectly good exceptions
>>> class A(object):
... def __init__(self):
... self.x = 2
... def f(self, x):
... print x == self.x
...
>>> obj = A()
>>> getattr(obj, 'floop')(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'floop'
>>> getattr(obj, 'x')(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> getattr(obj, 'f')(1)
False
>>>
--
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list