Generating methods in a class

Remy Blank remy.blank_asps at pobox.com
Tue Jul 6 09:13:06 EDT 2004


C GIllespie wrote:
> I have a class the looks something like this:
> 
> class file:
>     def __init__(self):
>         pass
> 
>     def file2ps(self):
>          return 'ps'
> 
>     def file2jpg(self):
>          return 'jpg'
> 
>     def file2gif(self):
>          return 'gif'
>     etc
> 
> What is a quick way of generating all these methods?

What about this:

 >>> class myFile:
... 	formats=['ps', 'ps2', 'pcl']
... 	for frmt in formats:
... 		exec "def file2%s(self): return '%s'" % (frmt, frmt)
... 	del frmt
...
 >>> dir(myFile)
['__doc__', '__module__', 'file2pcl', 'file2ps', 'file2ps2', 'formats']
 >>> f = myFile()
 >>> f.file2pcl()
'pcl'
 >>>

HTH,
-- Remy


Remove underscore and anti-spam suffix in reply address for a timely 
response.



More information about the Python-list mailing list