[tutor] functions and classes

alan.gauld@bt.com alan.gauld@bt.com
Wed Oct 23 13:01:02 2002


> def compare(x,y): # this is what I think the compare should look like
> def disbatch(choice): # this is what I think the disbatch 

They look OK to me apart from some typos.

> the next question is When I define a class do I import these 
> then use them by calling them then define the class or do I 
> do that afterwards

Depends what you want to do.
Assuming you oput the two functions in a file called 
httlacs4.py (How to think....4!)

You can import the file and use the functions before 
defining a class:

import httlacs4 as h    # I'm lazy!

h.compare(4,5)
h.disbatch("A")   

# - OOPs probably an error unless functionA has been written too...

class foo:
  pass

Or you could define the class before the calls to compare/disbatch.

What you can't do is call or even reference the functions 
before you do the import. Thus you couldn't use compare 
inside the class unless you put the import before the 
class definition.

As a general rule its best to

1) Do any imports necessary
2) define any data types/classes/functions
3) write executable code(like calling compare etc)

in that order.

It also makes it easier to debug if you follow that structure consistently.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld