Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A <em>class</em> consists basically of data (attributes) and a collection of functions (methods) to operate on that data. Each <em>instance</em> of a class has its own copy of the data, but shares the methods.</p> <p>Thus, every<sup>*</sup> method of a class operates on some instance of the class, so the method needs to know <em>what</em> instance it is operating on. That's what <code>self</code> is for -- <code>self</code> just means the instance that a method is working with.</p> <p>So, for example:</p> <pre><code>class House: def renovate(self): ''' Renovate a house, increasing its value. ''' self.value += 10000 oldhouse = House() # make a House instance that has no attributes oldhouse.value = 100000 # set an attribute of the House mansion = House() mansion.value = 10000000 oldhouse.renovate() # self will be set to oldhouse, so that oldhouse's value goes up print oldhouse.value # prints 110000 print mansion.value # prints 10000000: it hasn't changed because renovate knew what it was operating on </code></pre> <p>Now, in this example, note that I set <code>.value</code> outside the class. You can do that (Python lets you set any attributes on almost any instance), but it's kind of cumbersome to do that for every class.</p> <p>This is where <code>__init__</code> comes in. It's a method with special meaning (hence the double underscores). In this case, it's a method which is called when the class gets created (when you call the class with parens to make a new instance). <code>init</code> here stands for <code>initialization</code>: it's a function that initializes the class attributes. Any arguments it takes (beyond <code>self</code>) will be expected when you create the class.</p> <p>So, we could change our example to this:</p> <pre><code>class House: def __init__(self, value): self.value = value # set attribute def renovate(self): ''' Renovate a house, increasing its value. ''' self.value += 10000 oldhouse = House(100000) # make a House instance with the value set mansion = House(10000000) # make another House instance with the value set oldhouse.renovate() print oldhouse.value # prints 110000 print mansion.value # prints 10000000 </code></pre> <p>and it would work the same, but be somewhat nicer (since we don't have to keep setting <code>.value</code> on new <code>House</code>s).</p> <hr> <p><sup>*</sup> except staticmethods and classmethods, and special cases like <code>__new__</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload