Is it necessary to include __init__ as the first function every time in a class in Python?

No, it isn't necessary.

For example.

class A(object):
    def f():
        print 'foo'

And you can of course use it, in this manner:

a = A()
a.f()

In fact you can even define a class in this manner.

class A:
    pass

However, defining __init__ is a common practice because instances of a class usually store some sort of state information or data and the methods of the class offer a way to manipulate or do something with that state information or data. __init__ allows us to initialize this state information or data while creating an instance of the class.

Here is a complete example.

class BankAccount(object):
    def __init__(self, deposit):
        self.amount = deposit

    def withdraw(self, amount):
        self.amount -= amount

    def deposit(self, amount):
        self.amount += amount

    def balance(self):
        return self.amount

# Let me create an instance of 'BankAccount' class with the initial
# balance as $2000.
myAccount = BankAccount(2000)

# Let me check if the balance is right.
print myAccount.balance()

# Let me deposit my salary
myAccount.deposit(10000)

# Let me withdraw some money to buy dinner.
myAccount.withdraw(15)

# What's the balance left?
print myAccount.balance()

An instance of the class is always passed as the first argument to a method of the class. For example if there is class A and you have an instance a = A(), whenever you call a.foo(x, y), Python calls foo(a, x, y) of class A automatically. (Note the first argument.) By convention, we name this first argument as self.


In addition to other answers, one point in your question that has not been addressed :

Is it necessary to include __init__ as the first function everytime in a class in Python?

The answer is no. In the case you need a constructor, it can be located at any position of your code, although the conventional and logical place is the beginning.


You don't need to put it in your Class, it is the object constructor.

You will need it if you want things to happen automatically to your object when it is instanciated.

Tags:

Python