"Shurui Liu (Aaron Liu)" <shuru...@gmail.com> wrote

Sorry, let me specify. I think comptuter will print out those two
sentences like this:

A new critter has been born!
Hi.  I'm an instance of class Critter.
A new critter has been born!
Hi.  I'm an instance of class Critter.

class Critter(object):
"""A virtual pet"""
def __init__(self):
print "A new critter has been born!"

Here you are calling print inside the constructor (actually the initialiser)
method which gets called when you create a new object

def talk(self):
print "\nHi. I'm an instance of class Critter."

Here you are calling print inside a method that only gets executed
when explicitly called from the created object


crit1 = Critter()
crit2 = Critter()

Here you create two objects so the constructor method will be executed twice.
So you get the message

A new critter has been born!"

twice.

crit1.talk()
crit2.talk()

Then you call the talk method for each object so you get

Hi. I'm an instance of class Critter.

twice.

The __init__() method is nothing too special. It gets called
automatically when you create the object is all. You can think
of

crit = Critter()

as effectively being a call to Critter.__init__()

There is a little bit more to it that that but most of the time its
close enough.

You can read an alternative explanation in the OOP topic
of my tutorial...

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to