Python Introduction | Using Classes | Using Constructors

The Member class is still not especially useful. Creating an instance, setting name, and calling showMsg one step at a time is not very different from working without a class. In addition, if you forget to set a member variable after creating an instance, the program will not behave as expected. At minimum, required values should be set correctly from the beginning.

A constructor is useful in this situation. A constructor is a special method for initializing an instance that is called automatically when the instance is created. Define one as follows.

def __init__(self, arguments...):
    ... initialization ...

Define a constructor as a method named __init__. To pass values to it, specify them from the second argument onward. The first argument must always be self.

Once a constructor is defined, it is used when an instance is created. Consider the following example.

class Member: 
    name = "" 
   
    def __init__(self, str): 
        self.name = str
   
    def showMsg(self): 
        print("Hello," + self.name + ".How are you?") 
   
taro = Member("Taro") 
taro.showMsg() 
   
hanako = Member("Hanako") 
hanako.showMsg()

This example defines a constructor that receives an argument named str.

def __init__(self, str):

The name value must now be supplied when an instance is created. Look at the statement that creates an instance.

taro = Member("Taro")

The name is passed as an argument inside the parentheses. Allowing arguments to be specified when creating an instance is convenient because required member variables can be initialized at the same time.