calling __init__ more than once?

Joal Heagney s713221 at student.gu.edu.au
Sun Sep 2 20:27:35 EDT 2001


Roy Smith wrote:
> 
> I've got a file parsing class which in which I call a single parser object
> repeatedly to parse additional files.  Something like:
> 
>    p = myParser()
>    stuff1 = p.parse (fileName1)
>    stuff2 = p.parse (fileName2)
> 
> Is there any reason why my parse method couldn't call __init__() to reset
> things back to the start state?  It feels kind of creepy, but I don't see
> any reason why it should be a problem.  Is there something I'm missing
> here, or is it really OK to call __init__() again?

>>> class test:
...     def __init__(self, *args, **kargs):
...             self.args = args
...             self.kargs = kargs
...
>>> a = test('hello', Joal='cool')
>>> a.args
('hello',)
>>> a.kargs
{'Joal': 'cool'}
>>> a.__init__('hello', Joal='not')
>>> a.args
('hello',)
>>> a.kargs
{'Joal': 'not'}

Doesn't seem to have any ill effects. If you're really uncomfortable
about re-calling the __init__ function when not initializing, how about
creating a second function and applying it from within __init__. Then
later you can call this function direct.

>>> class test2:
...     def clear(self, *args, **kargs):
...             self.args = args
...             self.kargs = kargs
...     def __init__(self, *args, **kargs):
...             apply(self.clear, args, kargs)
...
>>> b = test2('hello', Joal='cool')
>>> b.args
('hello',)
>>> b.kargs
{'Joal': 'cool'}
>>> b.clear('goodbye', Joal='not')
>>> b.args
('goodbye',)
>>> b.kargs
{'Joal': 'not'}
-- 
      Joal Heagney is: _____           _____
   /\ _     __   __ _    |     | _  ___  |
  /__\|\  ||   ||__ |\  || |___|/_\|___] |
 /    \ \_||__ ||___| \_|! |   |   \   \ !



More information about the Python-list mailing list