Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Let’s take a simple vector class:</p> <pre><code>class Vector: def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?</p> <pre><code> def length(self): return math.sqrt(self.x ** 2 + self.y ** 2) </code></pre> <p>What should it look like when we were to define it as a global method/function?</p> <pre><code>def length_global(vector): return math.sqrt(vector.x ** 2 + vector.y ** 2) </code></pre> <p>So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a <code>length</code> method for our <code>Vector</code> class, we could do this:</p> <pre><code>Vector.length_new = length_global v = Vector(3, 4) print(v.length_new()) # 5.0 </code></pre> <p>This works because the first parameter of <code>length_global</code>, can be re-used as the <code>self</code> parameter in <code>length_new</code>. This would not be possible without an explicit <code>self</code>.</p> <hr> <p>Another way of understanding the need for the explicit <code>self</code> is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like</p> <pre><code>v_instance.length() </code></pre> <p>is internally transformed to</p> <pre><code>Vector.length(v_instance) </code></pre> <p>it is easy to see where the <code>self</code> fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.</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. 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