Calling class method by name passed in variable

S

Sagari

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?

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.
 
G

Gary Herron

Sagari said:
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
 
B

Bruno Desthuilliers

Sagari a écrit :
Greetings,

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)
 
B

Bruno Desthuilliers

Nick Craig-Wood a écrit :
I think that that is needless LBYL...

From experience, it isn't.

getattr(obj, 'method_name')(args)

Will produce some perfectly good exceptions

The problem is that you can't tell (without reading the exception's
message and traceback etc) if the exception happened in you code or
within the called method.
 
S

Sagari

Thanks to everyone for the advice. In fact, since all the called
methods trap necessary exceptions, I see no big problems with that.

With all respect,

Konstantin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top