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?
No, it isn’t necessary.
For example.
And you can of course use it, in this manner:
In fact you can even define a class in this manner.
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.
An instance of the class is always passed as the first argument to a method of the class. For example if there is
class Aand you have an instancea = A(), whenever you calla.foo(x, y),Pythoncallsfoo(a, x, y)ofclass Aautomatically. (Note the first argument.) By convention, we name this first argument asself.