instance creation

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Sep 24 05:58:14 EDT 2002


paulmg at digitalbrain.com (Paul MG) wrote in 
news:265e380f.0209240052.4c2988f3 at posting.google.com:

> - Having two constructors seems to be illegal - or at least the second
> overwrites the first.
> - Assigning to 'self' in the load method seems to really not work!
> - Putting the create() method outside of the class works fine - but I
> want it to be a class method on Appointment, goddammit!:) Is there no
> way to do this?
> 
> Any help would be appreciated, basically i am looking for the python
> idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in
> the grain of the language!
> 

First off, you want to use a single function and check what arguments were 
passed. For example:

    def __init__(self, name=None, details=None, id=None):
    	 if id is not None:
          assert name==details==None
          i = open("appointment"+str(id))
          tmp = pickle.load(i)
          self.name, self.details = tmp.name, tmp.details
      else:
          self.name = name
          self.details = details

Then you can call the constructor using keyword arguments as appropriate:
    x = Appointment(id='49')
    y = Appointment('Me', 'Something')
    y = Appointment(name='Me', details='Something') # Same as above

You could avoid using keyword arguments and just count the number of 
arguments passed in if you preferred.

If you want to get rid of the extra object and copying of name and details 
you could just pickle the individual fields instead of pickling the whole 
object, or you could use the __new__ method.

__init__ is called when the object already exists to complete its 
initialisation. __new__ is called before the object is created and allows 
you to modify the actual creation of the object. You have to subclass a 
type such as object for __new__ to work:

class Appointment(object):
    def __new__(cls, name=None, details=None, id=None):
      if id is not None:
          assert name==details==None
          i = open("appointment"+str(id))
          return pickle.load(i)
      else:
          self = object.__new__(cls)
          self.name = name
          self.details = details
          return self

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list