473,769 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2996
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************ ********@websit eburo.invalidwr ote:
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************ ********@websit eburo.invalidwr ote:
>>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************ ********@websit eburo.invalidwr ote:
Nick Craig-Wood a ?crit :
Bruno Desthuilliers <br************ ********@websit eburo.invalidwr ote:
>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
1675
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 correspond to actual variables with values that are passed into the preSelect() function inside the methods (that function is called from an outside parent script included). However, upon careful inspection the global function does not globalize...
5
15371
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 the same class/static method definition statictly linked to my EXE and when I call InvokeMember(...), even though I got the Type from the new AppDomain, it calls the static method that I am staticly linked to and not the static method in the dynamicly...
11
1781
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'); resetMenu(sel); } function resetMenu(sel){ sel.length = 0;
2
2066
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 ... If I instantiate the proxy class, I can set its Url property localhost.Sender oSender = new localhost.Sender(); // proxy clas oSender.Url = "http://server/webservice/s.asmx"
6
2551
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? It seems like including "parent" in the class def is just like a class variable, which most do not recommend. An example: class LXSerial: def __init__(self, parent, debug=False): ...
5
5020
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
2255
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 do is call a generically named public sub in the top-most sub form in the panel. I have the name of the top-most form as a string (eg. g_TopForm = "frmCustomers") and I can reference the form with:
8
1989
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 __init__(self,some_super): some_super.__init__(self) if some_super == list: self.append('ABC')
20
4043
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 tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
0
9586
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10043
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.