[Tutor] Re-instantiate within __init__

Alan Gauld alan.gauld at freenet.co.uk
Wed Apr 19 19:24:47 CEST 2006


> is it correct that an object cannot be re-instantiated within it's 
> __init__ method?

There are some tricks you can pull but the object is actually instantiated
before the init gets called. Really init is for initialisation of the 
instance,
it's not a true constructor.

> Background: I need to create a new object upon instantiation
> when a database query returns no records.

I'd probably create a factory function to do this that
returns the appropriate type of instance.

def makeDbResponseInstance(queryStatus):
      if queryStatus:
         return DBClass()
      else: return Emptyclass()

If the two classes are subclassed from a common ancestor you
might put the factory into the class as a class method, but I'd
probably just keep it as a function. That keeps the two class's
definitions clean and decoupled from the instantiation decision
which isn't really their responsibility - children don't choose to be
born!.

Alan G. 



More information about the Tutor mailing list