Sagari wrote:
Greetings,

Can someone suggest an efficient way of calling method whose name is
passed in a variable?

Given something like:

class X:
#...
  def a(self):
# ...

  def b(self):
# ...

#...

x = X()
#...
v = 'a'

How do I call the method of x  whose name is stored in v?

Use getattr (stands for get attribute) to do this.

   fn = getattr(x, v)  # Get the method named by v
   fn(...)    # Call it

Or in one line:

   getattr(x,v)(...)


Gary Herron


PHP code for this would be:

class X {
  function a() {
  }
}

$x = new X();
$v = 'a';
$x->$v();

I need a solution for Python. Could you suggest anything?

The task it to call a function whose name is taken from user-supplied
input.

Thanks.
--
http://mail.python.org/mailman/listinfo/python-list

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to