Call a classmethod on a variable class name
gherron at islandtraining.com
Sun Apr 13 17:18:53 CEST 2008
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.className
> 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
> 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
parameters.theClass = SomeClass
If you can't do that, then look up that class from the class name and
make your call:
parameters.className = 'SomeClass'
theClass = globals()[parameters.className]
(Hint: It matters not whether foo is a classmethod, saticmathod or
More information about the Python-list