472,961 Members | 2,151 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,961 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 2202
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: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.