Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Dead simple, just nest your functions:</p> <pre><code>def make_multiplier(x): def multiplier(y): return x * y return multiplier </code></pre> <p>Nested functions automatically look up unknown variables (<code>x</code> in this case) from their surrounding scope, using the value of <code>x</code> as it was when the outer function was called. The thing to remember here is that functions are just objects too, you can store them in a variable just like you can with other python objects, and defer calling them.</p> <p>This gives:</p> <pre><code>&gt;&gt;&gt; def make_multiplier(x): ... def multiplier(y): ... return x * y ... return multiplier ... &gt;&gt;&gt; f = make_multiplier(10) &gt;&gt;&gt; f(1) 10 &gt;&gt;&gt; f(2) 20 &gt;&gt;&gt; g = make_multiplier(5) &gt;&gt;&gt; g(1) 5 &gt;&gt;&gt; f(3) 30 </code></pre> <p>Note how <code>g</code> was given a different value for <code>x</code>, which is independent from the value for <code>x</code> in <code>f</code>.</p> <p>You could use a lambda as well; lambdas are just anonymous functions limited to one expression; that's enough here:</p> <pre><code>def make_multiplier(x): return lambda y: x * y </code></pre> <p>Another alternative technique is binding <code>x</code> to a keyword parameter, which means you could override it if you so wish:</p> <pre><code>def make_multiplier(x): def multiply(y, x=x): return x * y return multiply </code></pre> <p>or the lambda version:</p> <pre><code>def make_multiplier(x): return lambda y, x=x: x * y </code></pre> <p>and then pass in one or two arguments to the returned callable:</p> <pre><code>&gt;&gt;&gt; f = make_multiplier(10) &gt;&gt;&gt; f(5) 50 &gt;&gt;&gt; f(5, 3) 15 </code></pre>
    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