473,320 Members | 2,117 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Generating methods in a class

Dear All,

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? I'm thinking along the
lines of:
class file:
formats=['ps', 'ps2', 'hpgl', 'pcl', 'mif', 'pic', 'gd', 'gd2', 'gif',
'jpg']
def __init__(self):
for frmt in self.formats:
self.__setattr__('file2'+frmt, ???)

I've tried a variety of things where ??? is, but with no success.

Any ideas?

Thanks

Colin
Jul 18 '05 #1
4 2209
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.
Jul 18 '05 #2
On Tue, 6 Jul 2004, C GIllespie wrote:
What is a quick way of generating all these methods? I'm thinking along the
lines of:
class file:
formats=['ps', 'ps2', 'hpgl', 'pcl', 'mif', 'pic', 'gd', 'gd2', 'gif',
'jpg']
def __init__(self):
for frmt in self.formats:
self.__setattr__('file2'+frmt, ???)

I've tried a variety of things where ??? is, but with no success.


You've probably tried using ??? = lambda: frmt, with the effect that all
the functions return 'jpg'. This has bit me before, too. The problem with
this approach is that frmt is not evaluated inside the lambda -- after the
loop has finished, you end up with a bunch of "lambda: frmt"s, and frmt is
left equal to "jpg". The way to fix this is to force frmt to be evaluated,
as follows:

class file:
formats=['ps', 'ps2', 'hpgl', 'pcl', 'mif', 'pic', 'gd', 'gd2', 'gif',
'jpg']
def __init__(self):
for frmt in self.formats:
setattr(self, 'file2'+frmt, self.genfunc(frmt))

def genfunc(self,frmt):
return lambda: frmt

Calling genfunc() forces frmt to be evaluated before being re-bound and
passed to the lambda.

There are a couple of problems with placing this all in __init__, however:
the functions are generated each time you create a new file object, and
they aren't passed a "self" reference. To fix these problems, it's best to
add all the methods to the class itself, and not the individual objects:

class file:
formats=['ps', 'ps2', 'hpgl', 'pcl', 'mif', 'pic', 'gd', 'gd2', 'gif',
'jpg']

def genfunc(frmt):
return lambda self: frmt
genfunc=staticmethod(genfunc)

for frmt in file.formats:
setattr(file, 'file2'+frmt, file.genfunc(frmt))

Note that neither formats nor genfunc() need to be members of file; if it
suits your taste better, the same thing can be written as:

class file:
pass

formats=['ps', 'ps2', 'hpgl', 'pcl', 'mif', 'pic', 'gd', 'gd2', 'gif',
'jpg']

def genfunc(frmt):
return lambda self: frmt

for frmt in formats:
setattr(file, 'file2'+frmt, genfunc(frmt))

Personally, I prefer the version using static attributes of the class, but
either way will work as well.

Jul 18 '05 #3
C GIllespie wrote:
Dear All,

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


Actually, I don't think it's a good idea---I'd rather prefer something like:

class file:
<skipped>
def convert(self, type):
return type

with further dispatch on type if needed or just a bunch of functions put
into a dictionary.

If you insist on methods you can take a look on __getattr__ machinery.

And the last: `file` seems to be a bad name as it hides standard `file`
class.

regards,
anton.
Jul 18 '05 #4
Thanks for all you help and suggestions

Colin
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

99
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less...
7
by: Conor Maguire | last post by:
Folks, We have a C# method which we register as part of a class for COM Interop: public void send(string contents, string filepath ,string filename) {
18
by: Elder Hyde | last post by:
Hey all, A class of mine needs to tell the outside world when its buffer is not empty. The problem is that C# seems to force you to put the event-raising code in the base class. To illustrate,...
1
by: Adam Clauss | last post by:
Alright, so I've got a class library that others will be using. When you hover the mouse over most of the exiting .NET classes/methods, you will get a tooltip popup showing the full...
3
by: Raed Sawalha | last post by:
Hello when I serialize an object an error generated using this function public string SerializeObject(object oClassObject,System.Type oClassType) { XmlSerializer oSerializer = new...
4
by: Daniel Nogradi | last post by:
Is it possible to have method names of a class generated somehow dynamically? More precisely, at the time of writing a program that contains a class definition I don't know what the names of its...
1
by: louis_la_brocante | last post by:
Dear all, I am having trouble generating a client proxy for a webservice whose methods return a "complex" type. The type is complex in that it is a class whose members are a mix of primitive...
5
by: Miraj Haq | last post by:
Hi, I was amazed to see the new feature of "Insert Comment" on right click context menu over a sub routine or a class in vb.net. I can see using standard commenting mechanism, i can see help...
9
by: Cesar | last post by:
Hello there, A java programmer sent me a wsdl file, which I have to use to consume his web methods. When I run the wsld.exe tool to generate the class' code, I get the following message: ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.