If the main constructor is called with provided arguments,
__init__ will be passed using those arguments.
Examples of __init__
One of the most common and easy to understand examples of the
__init__ method can be found in the
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
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,
myExpensiveCar is a simple affair:
>>>myLittleCar.make 'Honda' >>>myLittleCar.model 'Civic' >>>myBigCar.make 'Mercedes' >>>myBigCar.model 'GL450' >>>myExpensiveCar.make 'Bugatti' >>>myExpensiveCar.model 'Veyron'
Examples of __init__ using default values
As with other functions,
__init__ can be passed using default values.
As in our previous example, we will define an
class Account: def __init__(self, balance = 0, owner = 'Bank'): self.balance = balance self.owner = owner
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
0 and the