473,387 Members | 1,678 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Calling class method by name passed in variable

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.
Jun 27 '08 #1
6 2977
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
Jun 27 '08 #2
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)
Jun 27 '08 #3
Bruno Desthuilliers <br********************@websiteburo.invalidwrote :
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 <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #4
Nick Craig-Wood a écrit :
Bruno Desthuilliers <br********************@websiteburo.invalidwrote :
>>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...
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.

Jun 27 '08 #5
Bruno Desthuilliers <br********************@websiteburo.invalidwrote :
Nick Craig-Wood a ?crit :
Bruno Desthuilliers <br********************@websiteburo.invalidwrote :
>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...

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.
I guess it depends on whether you are expecting it to ever fail or
not. If a user types in method_name then yes you are right checking
stuff and producing a nice error is good. However if it is part of
your internal program flow and you never expect it to go wrong in
normal operation then I'd be quite happy with the exception and
backtrace to debug the problem.

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Jun 27 '08 #6
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
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Phil Powell | last post by:
The following class is supposed to produce a series of HTML dropdowns and HTML text fields based solely upon variable names for month, day and year passed into it. Those variable names will...
5
by: Chris | last post by:
Hi I have a scenario where I've created another AppDomain to dynamically load a DLL(s) into. In this newly loaded DLL I want to call a static method on a class. The problem arise is that I have...
11
by: JS | last post by:
I have made a function createFirstMenu where I call "resetMenu" in a JavaScript. But nothing happens when I call resetMenu. function createFirstMenu(sel){ sel = document.getElementById('sel1');...
2
by: Stan | last post by:
I need to change the Url property in a web service proxy class in a generic way. The proxy class looks like this public class Sender : System.Web.Services.Protocols.SoapHttpClientProtocol ... ...
6
by: Ray Schumacher | last post by:
What is the feeling on using "parent" in a class definition that class methods can refer to, vs. some other organization ? Should all relevant objects/vars just be passed into the method as needed?...
5
by: sfeher | last post by:
Hi All, I need to call a function(loaded with appendChild) for which I have the name as a string. .... var fnName = 'fn1'; var call = fnName + '('+ param +' )'; eval(call);
4
by: Bugs | last post by:
Hi, I wonder if anyone can help me out. I'm building a vb.net application that has a form with a panel that contains several other sub forms (as a collection of controls). What I'm wanting to...
8
by: Jackson | last post by:
I want a class that will determine its base class by the argument passed in. What I am about to write _does_not_work_, but it shows what I am trying to do. class ABC(some_super): def...
20
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.