4

Possible Duplicate:
Python init and self what do they do?

Can anyone explain what __init__(self) does? I've been reading other questions and people mentioning super classes? What's a super class? I thought procedures were supposed to start off with

def print_word(word):
    print word

Is __init__(self) some sort of special case since it has underscores and "self"? sorry for the lack of specific terminology... still learning.

Community
  • 1
  • 1
bigpotato
  • 26,262
  • 56
  • 178
  • 334

5 Answers5

9

__init__(self) is a special function used within what are called "classes". Classes let you define your own datatypes/object and this __init__ function is called when ever you create a new instance of the datatype/object that you've defined. It's like saying "hey, every time you make one of these things, make sure you run this code too". In object oriented programming, we call this kind of function a "constructor". It's a function that's used to "construct" a new object. The self is a reference to the object that's actually being created. In other words, the object is technically already created by the time you get to your __init__ function. __init__ just gives you the opportunity to initializes various aspects of your object (hence the name __init__).

Python is a mixture of both functional, procedural, and object oriented paradigms. This __init__ business has to do with objects. For more information on object oriented programming you can checkout the wikipedia article.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
4

__init__ is the constructor of a class in Python. The methods that are bracketted by __ in a class have special meanings (constructory, operator implementation etc.).

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
  • 2
    Technically, it's not a constructor. – Wooble Jul 26 '12 at 16:47
  • 1
    The technical difference is usually unimportant in practice, unless you're dealing with advanced Python techniques, e.g. metaclasses, that most programmers won't ever touch. – atomicinf Jul 26 '12 at 16:49
  • Initialiser perhaps... `__new__` would be the constructor. – Noufal Ibrahim Jul 26 '12 at 16:49
  • `__new__` isn't exactly a constructor either, more of a malloc/reference lookup system for class instances themselves depending upon what you do with it... to me, it seems like `__new__` and `__init__` both do parts of what a traditional constructor does, but also do things outside of that job. Seems best to just avoid the whole question by saying `__new__` creates and/or retrieves instance references, and `__init__` populates the initial state of instances. – Silas Ray Jul 26 '12 at 17:04
4

To understand the role of __init__(self, ...) you have to understand classes first.

A class basically defines a type of object. For example, if I wanted to define how a Fish behaves, I might start out with something of the form

class Fish:
    def swim(self):
        print "I'm swimming!"
    def breathe(self):
        print "I'm breathing!"

However, that's not a very useful class because, while we've defined what a Fish can do, we don't know how to store other essential qualities about the Fish, e.g. how heavy it is.

In principle, if I have a Fish named f, I could just do

f.weight = 3

But if I forget to do that for some Fish, say a Fish named g, and then try to use g.weight in an expression, Python won't be very happy - it'll throw an AttributeError complaining that Fish instance has no attribute 'weight'.

To avoid that, we can define a constructor for our class that, every time a new Fish is created, sets properties like its weight and its color and whatever else you define to sensible default values. In Python, this constructor function is called __init__. As long as you define it in a class, it will be called every time a new instance of that class is created.

class Fish:
    def __init__(self):
        self.weight = 3
    def swim(self):
        print "I'm swimming!"
    def breathe(self):
        print "I'm breathing!"

Every function you define for a class takes an implied argument, which we usually label as self. This first argument is always set to the instance on which you're calling the function. For instance, if I invoke

f = Fish()
f.swim()

Python creates a Fish, puts it in f, then calls Fish.__init__(f) and Fish.swim(f) on it. In this case, the Fish in f will have its weight set to 3 and will cause "I'm swimming!" to be printed.

You can create class functions that don't need to take the self argument, called static functions, but those are useful only for specific cases you probably won't encounter for a while. Class functions in Python will usually be instance functions, which will take the self argument implicitly.

Note that, in the above example, every Fish created will have its default weight set to 3. What if we want to specify a Fish's weight at the time of creation? Well, we can define __init__() to take some extra arguments:

class SuperFish:
    def __init__(self, weight = 3):
        self.weight = weight

Note that the weight argument has a default value defined as 3. Thus, it is in fact optional for us to specify the weight. If we had just said def __init__(self, weight): instead, then specifying the weight would be required.

We can now perform any one of the following invocations:

a = SuperFish() # creates a SuperFish with a weight of 3
b = SuperFish(42) # creates a SuperFish with a weight of 42
c = SuperFish(weight = 9001) # creates a SuperFish with a weight of 9001

Hope that clears things up for you :)

atomicinf
  • 3,596
  • 19
  • 17
3

Possible duplicate: Python __init__ and self what do they do?

def print_word(word) is a function (or method/procedure). __init__(self) is a function used within a class.

This section of the Python tutorial on classes describes the __init__ function. I'd highly recommend reading that entire page, btw.

self is an arbitrary choice of a word to refer to the class itself; if you wanted, you could use watermelon. See: What is the purpose of self?

Python class functions wrapped with the double underscore have a special meaning. Another example is __str__. This section of PEP8 (an important Python style document) explains the meaning of underscores in Python.


Superclasses:

Community
  • 1
  • 1
Lenna
  • 1,445
  • 9
  • 21
0

self refers to the object itself and __init__ is a constructor that initialize the fields of that "self". For example, you're creating a Person class with fields "name" and "age". In __init__, you can set the default name to "Bob" and age to 36 by doing :

def __init__(self):
    self._name = "Bob"
    self._age = 36

That way, each time you create a new Person object, the default name and age will be set to "Bob" and 36.

Wilduck
  • 13,822
  • 10
  • 58
  • 90
Dao Lam
  • 2,837
  • 11
  • 38
  • 44