Call a classmethod on a variable class name

Arnaud Delobelle arnodel at googlemail.com
Sun Apr 13 05:01:31 EDT 2008


On Apr 13, 9:51 am, Matthew Keene <dfg... at yahoo.com.au> 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.className
>   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




More information about the Python-list mailing list