Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No, it isn't necessary.</p> <p>For example.</p> <pre><code>class A(object): def f(): print 'foo' </code></pre> <p>And you can of course use it, in this manner:</p> <pre><code>a = A() a.f() </code></pre> <p>In fact you can even define a class in this manner.</p> <pre><code>class A: pass </code></pre> <p>However, defining <code>__init__</code> is a common practice because instances of a class usually store some sort of state informtion or data and the methods of the class offer a way to manipulate or do something with that state information or data. <code>__init__</code> allows us to initialize this state information or data while creating an instance of the class. </p> <p>Here is a complete example.</p> <pre><code>class BankAccount(object): def __init__(self, deposit): self.amount = deposit def withdraw(self, amount): self.amount -= amount def deposit(self, amount): self.amount += amount def balance(self): return self.amount # Let me create an instance of 'BankAccount' class with the initial # balance as $2000. myAccount = BankAccount(2000) # Let me check if the balance is right. print myAccount.balance() # Let me deposit my salary myAccount.deposit(10000) # Let me withdraw some money to buy dinner. myAccount.withdraw(15) # What's the balance left? print myAccount.balance() </code></pre> <p>An instance of the class is always passed as the first argument to a method of the class. For example if there is <code>class A</code> and you have an instance <code>a = A()</code>, whenever you call <code>a.foo(x, y)</code>, <code>Python</code> calls <code>foo(a, x, y)</code> of <code>class A</code> automatically. (Note the first argument.) By convention, we name this first argument as <code>self</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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