Python Programming for the Absolute Beginner, 3rd Edition

You've seen how you can create methods, like talk(), but there's a special method you can write, called a constructor, that is automatically invoked right after a new object is created. A constructor method is extremely useful. In fact, you'll almost always write one for each class you create. The constructor method is usually used to set up the initial attribute values of an object, though I won't use it for that in this program.

Introducing the Constructor Critter Program

The Constructor Critter program defines a new Critter class that includes a simple constructor method. The program also shows how easy it is to create multiple objects from the same class. Figure 8.5 shows a sample run of the program.

Figure 8.5: Two separate critters are created. Each says hi.

Here's the Constructor Critter program code:

# Constructor Critter # Demonstrates constructors # Michael Dawson - 3/23/03 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() crit1.talk() crit2.talk() raw_input("\n\nPress the enter key to exit.")

Creating a Constructor

The first new piece of code in the class definition is the constructor method (also called the initialization method):

def __init__(self, name): print "A new critter has been born!"

Normally, you make up your own method names, but here I used a specific one recognized by Python. By naming the method __init__, I told Python that this is my constructor method. As a constructor method, __init__() is automatically called by any newly created Critter object right after the object springs to life. As you can see from the second line in the method, that means any newly created Critter object automatically announces itself to the world by printing the string "A new critter has been born!".

HINT

Python has a collection of built-in "special methods" whose names begin and end with two underscores, like __init__, the constructor method.

Creating Multiple Objects

Once you've written a class, creating multiple objects is a snap. In the main part of the program, I create two:

# main crit1 = Critter() crit2 = Critter()

As a result, two objects are created. Just after each is instantiated, it prints "A new critter has been born!" through its constructor method.

Each object is its very own, full-fledged critter. To prove the point, I invoke their talk() methods:

crit1.talk() crit2.talk()

Even though these two lines of code print the exact same string, each is the result of a different object.

Категории