Polymorphing - how?

Cliff Wells logiplexsoftware at earthlink.net
Wed May 1 16:55:47 EDT 2002


On Wed, 01 May 2002 22:39:24 +0200
Jaros³aw Zabie³³o wrote:

> I would like to execute functions which names will be changed during
> runtime. The following approach does not work. :-(
> 
> def First(s):
> 	print "myFun1: %s" % s
> def Second(s)
> 	print "myFun2: %s" % s
> name = 'First'
> name('blah') # It doesn't work. :-(
> 			 # TypeError: 'str' object is not callable
> name = 'Second'
> name('blah') # Like above. 

Leave off the quotes:

name = First
name('blah')

However if you are going to use a string to reference the function, then I
suggest using a dictionary as a lookup table:

table = {
    'First': First,
    'Second': Second,
}

name = table['First']
name('blah')

It's also possible to use eval, but this isn't usually recommended:
name = eval('First')
name('blah')

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list