How to define a class that can create instances of computed type/class?

Pierre Rouleau prouleau_nospam at impathnetworks.com
Fri Dec 13 16:57:03 EST 2002


I am writing a Python module that performs operations and stores its 
data members inside a file.  The Python code must handle several file 
formats.  I don't have control over some of these file formats.  I have 
control over the furure file format.

I created a class Form1 that can read and write files of  format 1, and 
another class, Form2, that can read and write files of format 2.

I would like to define a class Form in such a way that it would 
recognize the file format and create an instance of the proper type.  I 
have something that does it.  I use a function to act as a class 
factory. The following code shows a simple example where Form1 and Form2 
are two independent classes that do not derive from the same base (but 
could be done without changing the interface).  The Form() function is 
used like a class factory.  It returns an instance of a class that 
corresponds to the selection criteria.

in t.py:

# ----------------------------------------------------------

whatever= 1

class Form1 :
    def __init__(self,value) :
       self.value= value
       self.theType = 'Form1'


class Form2 :
    def __init__(self,value) :
       """Create a unit."""
       self.value= value
       self.theType = 'Form2'

def Form(value):
    if whatever:
       return Form1(value)
    else:
       return Form2(value)
# ----------------------------------------------------------

It can be used like this:

 >>> import t
 >>> u = t.Form(6)
 >>> u
<t.Form1 instance at 0x007B0B00>
 >>> u.theType
'Form1'
 >>>
 >>> t.whatever=0
 >>> uu = t.Form(6)
 >>> uu
<t.Form2 instance at 0x007B09F0>
 >>> uu.theType
'Form2'
 >>>
# ----------------------------------------------------------

Now my question:

Is there a better way to do this?  Is it possible to create the same 
effect without using a function?

Thanks for the help!

	Pierre




More information about the Python-list mailing list