[Tutor] Class and methods?
Max Noel
maxnoel_fr at yahoo.fr
Thu Mar 31 01:01:13 CEST 2005
On Mar 31, 2005, at 00:44, Kevin wrote:
> 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?
>
> Thanks
> Kevin
Not exactly. By the time you instantiate a class, the program has
already started.
Let's take an example: an Image class. It contains all the stuff
needed to load, display, modify and save an image. These are the
load(), display() and save() methods, for example.
If you want to load an image from a file and display it somewhere on
the screen, what you would do is the following:
myImage = Image() # Creates a "blank" image
myImage.load("test.jpg") # Load the image from test.jpg
myImage.display(100, 100) # Displays the image at the position (100,
100)
Now, loading an image from the disk is actually a very common
operation with this class -- creating a blank image would probably be
the exception rather than the rule. Therefore, it makes sense to define
a __init__() method like this:
def __init__(self, fileName=None):
if fileName == None:
# Create a blank image...
else:
self.load(fileName)
__init__() is the method that's called with the arguments you supply
when instantiating the class. Since it is defined, you can now
instantiate the class with an argument:
myImage1 = Image("test.jpg") # Creates an image from the file "test.jpg"
myImage2 = Image() # Creates a blank image
Get the idea?
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting
and sweating as you run through my corridors... How can you challenge a
perfect, immortal machine?"
More information about the Tutor
mailing list