davea at ieee.org
Mon Apr 5 00:45:29 CEST 2010
Shurui Liu (Aaron Liu) wrote:
> I am studying about how to create a constructor in a Python program, I
> don't really understand why the program print out "A new critter has
> been born!" and "Hi. I'm an instance of class Critter." twice. I
> guess is because "crit1 = Critter() crit2 = Critter()" But I
> don't understand how did computer understand the difference between
> crit1 and crit2? cause both of them are equal to Critter(). Thank you!
> # Constructor Critter
> # Demonstrates constructors
> class Critter(object):
> """A virtual pet"""
> def __init__(self):
> print "A new critter has been born!"
> def talk(self):
> print "\nHi. I'm an instance of class Critter."
> # main
> crit1 = Critter()
> crit2 = Critter()
> raw_input("\n\nPress the enter key to exit.")
Critter is a class, not a function. So the syntax
crit1 = Critter()
is not calling a "Critter" function but constructing an instance of the
Critter class. You can tell that by doing something like
Notice that although both objects have the same type (or class), they
have different ID values.
Since you supply an __init__() method in the class, that's called during
construction of each object. So you see that it executes twice.
Classes start to get interesting once you have instance attributes, so
that each instance has its own "personality." You can add attributes
after the fact, or you can define them in __init__(). Simplest example
crit1.name = "Spot"
crit2.name = "Fido"
Then you can do something like
and you'll see they really are different.
More information about the Tutor