[Tutor] def __init__(self):

Alan Gauld alan.gauld at yahoo.co.uk
Tue Apr 26 04:55:17 EDT 2016


On 26/04/16 08:01, Santanu Jena wrote:
> Hi,
> 
> Pls let me why
> "
> def __init__(self):
> 
> "
> declaration required, what's the use of this one.Pls explain  me in
> details.

It is used to initialise object instances.
For example if you define a class Rectangle that has a length and width
and a method to calculate the area:.

class Rectangle:
    length = 0   # defaults in case we forget to add them
    width = 0
    def area(self):
       return self.length * self.width

That works after a fashion:

r = Rectangle()
r.length = 20
r.width = 10
print r.area()   # prints 200

But it is clumsy. It would be better to define the
length and width as part of the object creation. To
do that we add an __init__() method:


class Rectangle:
   def __init__(self, len, width):
      self.length = len
      self.width = width
   def area(self):
      return self.length * self.width

r = Rectangle(20,10)
print r.area()  # prints 200

So the init method allows us to initialise the values
of the data attributes of our objects at the time of
creation. (You can also call other methods inside init()
of course but that is less common)

You can read more about __init__() in my tutorial
at the end of the Raw Materials topic and again
in the OOP topic.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list