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

Viewed 79258

In Python, I want to know if it is necessary to include __init__ as the first method while creating a class, as in the example below:

class ExampleClass: 

    def __init__(self, some_message): 
        self.message = some_message 
        print "New Class instance created, with message:" 
        print self.message 

Also, why do we use self to call methods? Can someone explain the use of "self" in detail?

Also, why do we use pass statement in Python?

9 Answers

Is not necessary the "init" statement, besides the "pass" statement is just used for skip, either to the next part of the code, or just skip cause was reached a special part like an "if" statement.

I initially struggled with that question too then I realize it is just another way to store certain data to your object and that data can be passed to any object method you define since your instance method has a self argument that can point back to the data you created in the init method.

No, it is not necessary but it helps in so many ways. people from Java or OOPS background understand better. For every class instance, there is an object chaining that needs to complete when we instantiate any class by creating an object. If we don’t put it compiler/interpreter puts it. But when we need some action to be formed while creating an object then we must have to pass it.

first.py
-------
class A:
    def one(self):
        print("something")
second.py
----------
from first import A
class B:

    def test(self):
        a = A()
        x = a.one()
        print(x)
    test(any)
**output:**
something
None

Its not necessary... It's just function that runs everytime an object is created from your class... And it can be helpful if you want every object have some things in common

Related