[Tutor] Class and methods?

Alan Gauld alan.gauld at freenet.co.uk
Thu Mar 31 18:32:03 CEST 2005


> I am sorta starting to get it. So you could use __init__ to ask for
a
> file name to see if there is one in a folder or not if there is then
> open that file and conitue where that file left off. If its not
there
> create a new file with that name, then start the program? Or do I
have
> that all wrong?

There is nothing to stop you doing that, but in general init should
not include interactive operations. It would be better to capture the
filemname before creating the object and pass the filename into init
as a parameter.

Once inside init you can check if the filename is valid and either
open the file or issue an error(raise an exception maybe?) or open
a default filename instead, whatever you like. init is just a normal
method except that it gets called first and is *intended* to
initialise
the internal attributes of the object.

I'm not sure what you mean by "start the program", in general, after
init completes,  your program will continue from where you created
the object.

class C:
  def __init__(self, val):
    self.val = val
    print 'finished initialising'

def main():    # my main program...
  v = int(raw_input('Type a number> '))
  c = C(v)     # pass in the value
  for n in range(c.val):
     print 'hello there'

main()

So programme flow here is that we call
main(),
main calls C(v) which internally calls
C.__Init__(c,v)
We then return to main() to print out the hello messages and terminate

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list