Referencing vars, methods and classes by name

Terry Reedy tjreedy at udel.edu
Fri Feb 9 14:43:26 EST 2007


"Sagari" <boyandin at gmail.com> wrote in message 
news:1171008606.012968.106680 at p10g2000cwp.googlegroups.com...
| Thanks to everyone for all the comments. I am migrating from PHP to
| Python and I am looking for the means to port a controller code that
| would, roughly speaking, call a certain method of a certain class
| (both class and method names taken from user input). Putting aside
| input verification (by the moment I perform the call input must have
| been verified), what would be the recommended way of doing the trick?

Use getattr(ob, name).
Suppose
mod = <module with classes, imported as 'mod'>
cname = <class name from user>
mname = <method name from user>

Then
classobj = getattr(mod, cname)
methobj = getattr(classobj, mname)

However: Python generally uses methods for instance methods.  Would you be 
creating an instance of the class (easily done -- inst = classobj(args)) 
before calling the method?  If so, call methodobj(inst, args).  If not, I 
wonder I you should really be using (Python) classes.

Terry Jan Reedy






More information about the Python-list mailing list