Beginning Programming with Python For Dummies
Book image
Explore Book Buy On Amazon
A constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class. Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts. Constructors can also verify that there are enough resources for the object and perform any other start-up task you can think of.

The name of a constructor is always the same, __init__(). The constructor can accept arguments when necessary to create the object. When you create a class without a constructor, Python automatically creates a default constructor for you that doesn’t do anything. Every class must have a constructor, even if it simply relies on the default constructor. The following steps demonstrate how to create a constructor:

Open a Python Shell window.

You see the familiar Python prompt.

Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

class MyClass:
 Greeting = "
 def __init__(self, Name="there"):
  self.Greeting = Name + "!"
 def SayHello(self):
  print("Hello {0}".format(self.Greeting))

This example provides your first example of function overloading. In this case, there are two versions of __init__(). The first doesn’t require any special input because it uses the default value for the Name of “there”. The second requires a name as an input. It sets Greeting to the value of this name, plus an exclamation mark.

Python doesn’t support true function overloading. Many strict adherents to strict Object-Oriented Programming (OOP) principles consider default values to be something different from function overloading. However, the use of default values obtains the same result, and it’s the only option that Python offers. In true function overloading, you see multiple copies of the same function, each of which could process the input differently.

Type MyInstance = MyClass() and press Enter.

Python creates an instance of MyClass named MyInstance.

Type MyInstance.SayHello() and press Enter.

Type MyInstance.SayHello() and press Enter.

Notice that this message provides the default, generic greeting.

Type MyInstance = MyClass(“Amy”) and press Enter.

Python creates an instance of MyClass named MyInstance.

Type MyInstance.SayHello() and press Enter.

Type MyInstance.SayHello() and press Enter.

Notice that this message provides a specific greeting.

Close the Python Shell window.

Good job!

About This Article

This article can be found in the category: