473,883 Members | 1,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Call a classmethod on a variable class name

I would like to be able to call a specific classmethod on a class name
that is going to be passed from another parameter. In other words, I
have a call that looks something like:

x = Foo.bar()

and I would like to generalise this so that I can make this call on any
particular class which provides the bar classmethod.

I have implemented this using exec, like so:

className = parameters.clas sName
exec "x = " + className + ".bar()"

but this feels somewhat clumsy. (I do have the requisite exception
handling to cope with the supplied class not existing or not
implementing the bar method, by the way).

Is there any more Pythonesque way of doing this ? I guess what I'm
probably looking for is something like the way I understand the send
function works in Ruby
Jun 27 '08 #1
3 2387
On Apr 13, 9:51*am, Matthew Keene <dfg...@yahoo.c om.auwrote:
I would like to be able to call a specific classmethod on a class name
that is going to be passed from another parameter. *In other words, I
have a call that looks something like:

* *x = Foo.bar()

and I would like to generalise this so that I can make this call on any
particular class which provides the bar classmethod.

I have implemented this using exec, like so:

* className = parameters.clas sName
* exec "x = " + className + ".bar()"

but this feels somewhat clumsy. *(I do have the requisite exception
handling to cope with the supplied class not existing or not
implementing the bar method, by the way).

Is there any more Pythonesque way of doing this ? *I guess what I'm
probably looking for is something like the way I understand the send
function works in Ruby
If your class lives in the current global namespace, you can get it
with
>>cls = globals()[classname]
Then you can access its .bar() method directly:
>>cls.bar()
Example:
>>class Foo(object):
... @classmethod
... def bar(cls): print 'Oh my Baz!'
...
>>globals()['Foo']
<class '__main__.Foo'>
>>globals()['Foo'].bar()
Oh my Baz!

If your class lives in a module, just do getattr(module, classname)
instead to get the class object.

HTH

--
Arnaud

Jun 27 '08 #2
Arnaud Delobelle wrote:
>
If your class lives in the current global namespace, you can get it
with
>>cls = globals()[classname]

Then you can access its .bar() method directly:
>>cls.bar()

Example:
>class Foo(object):
... @classmethod
... def bar(cls): print 'Oh my Baz!'
...
>globals()['Foo']
<class ' main .Foo'>
>globals()['Foo'].bar()
Oh my Baz!

If your class lives in a module, just do getattr(module, classname)
instead to get the class object.

HTH

Yes, that feels much nicer and works well.

Thanks for the prompt reply !
Jun 27 '08 #3
Matthew Keene wrote:
I would like to be able to call a specific classmethod on a class name
that is going to be passed from another parameter. In other words, I
have a call that looks something like:

x = Foo.bar()

and I would like to generalise this so that I can make this call on any
particular class which provides the bar classmethod.

I have implemented this using exec, like so:

className = parameters.clas sName
exec "x = " + className + ".bar()"
Yuck. No. Don't do that. As a general rule, anything you could build
and put into an exec is a functionality that is exposed more directly by
Python.
but this feels somewhat clumsy. (I do have the requisite exception
handling to cope with the supplied class not existing or not
implementing the bar method, by the way).

Is there any more Pythonesque way of doing this ? I guess what I'm
probably looking for is something like the way I understand the send
function works in Ruby
First off, if possible, don't pass the class name, but instead pass the
class itself:

class SomeClass:
def foo():
... whatever...

...
parameters.theC lass = SomeClass
...
parameters.theC lass.bar()

If you can't do that, then look up that class from the class name and
make your call:

class SomeClass:
def foo():
... whatever...

...
parameters.clas sName = 'SomeClass'
...
theClass = globals()[parameters.clas sName]
parameters.theC lass.bar()
(Hint: It matters not whether foo is a classmethod, saticmathod or
normal method.)

Gary Herron



Jun 27 '08 #4

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

Similar topics

4
12009
by: bonono | last post by:
Hi, Suppose my class definition is like this : class A: name = "A" @classmethod def foo(cls): cls.__super.foo()
6
1708
by: Jeff Frederick | last post by:
Hello all, I am interested in using the value from a field to call a function. For example I have a table and one of the field names is "Function." So for each record I input the name of the function I want to run when this record is selected. Table Example: Shape Function -------------------
3
2150
by: andychambers2002 | last post by:
Hi, I'm trying to write a method that needs to know both the class name and the instance details class A: @classmethod def meth(cls, self): print cls
1
1134
by: Faheem Mitha | last post by:
Hi, Consider the following small script. My understanding of how this works is that, conceptually, class B holds a separate copy of variable x from class A. Nearly everything behaves the way I would expect, except that setting x to 12 in A using class_setx at the beginning also sets the value for x in B. However, the converse (setting x in B using class_setx), does
0
9944
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
11151
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
10752
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
10858
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
7134
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5804
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...
1
4619
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
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3238
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.