From CS 61A Wiki
Jump to: navigation, search

__init__ is an "initializer" Class constructor method that is passed every time a new instance of the Class is created. It's also known as an attribute of the instance of the class.

If the main constructor is called with provided arguments, __init__ will be passed using those arguments.

Examples of __init__

Bank Account

One of the most common and easy to understand examples of the __init__ method can be found in the Account class.

Consider the code below:

class Account:
   def __init__(self, balance):
      self.balance = balance

The only thing that matters to this Account is the balance. When we attempt to create a new Account, as below, we only need to pass in one argument (the balance we want). __init__ will automatically be called and apply our given balance to the new instance of Account we have created.

>>>myAccount = Account(500)

If we want to access myAccount's balance, we simply use the object.attribute notation as so:



Now suppose we want to create a Car class. We can define it as below, in which we only care about the make and model of the car.

class Car:
   def __init__(self, make, model)
      self.make = make
      self.model = model

If I want to create an instance of this Car class, I need to pass two arguments into my constructor, the make and the model. A couple examples are shown below.

>>>myLittleCar = Car('Honda', 'Civic')
>>>myBigCar = Car('Mercedes', 'GL450')
>>>myExpensiveCar = Car('Buggati', 'Veyron')

Accessing the variables for all instances, myLittleCar, myBigCar and myExpensiveCar is a simple affair:


Examples of __init__ using default values

As with other functions, __init__ can be passed using default values.

Bank Account

As in our previous example, we will define an Account class.

class Account:
   def __init__(self, balance = 0, owner = 'Bank'):
       self.balance = balance
       self.owner = owner

Whenever an Account class is instantiated, the constructor assumes the balance to be 0 and the owner to be 'Bank' unless explicitly told otherwise.

>>>myFirstAccount = Account()

This creates an Account instance where the balance is 0 and the owner is 'Bank'.


Rafe Kettler's Guide to Magic Methods: Construction and Initialization

Fall 2013 Lecture 15

Spring 2014 Lecture 15

Spring 2014 Discussion 6