[Tutor] __init__ for class instantiation?

Alan Gauld alan.gauld@blueyonder.co.uk
Fri Apr 25 20:39:01 2003


> My best current solution is to do just that. I can do it via
__init__, but
> this means the function I want to run once upon the class's
definition is
> actually called with every instance of the class. But I'm not going
to
> stress about the CPU cycles caused by this :)

Set a class variable to one the first time

def __init__(...):
   # do the usual stuff
   if not MyClass.flag:
      myClsass.flag = 1
      self.MySpecialMethod()

Then only the first instance calls the method, others just do
the if test.

OR

set it to None

def __init__(....):
    # usual stuff
    self.MySpecialMethod()
    self.MySpecialMethod = None  # note no parens!

First time through it calls it, subsequent times theres nothing
to call. You ight need to wrap a try/except round it too...

HTH,

Alan G.