Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Pass the instance explicitly as first argument:</p> <pre><code>method_to_use = order[i] method_to_use(my_pop) </code></pre> <p>Full working code:</p> <pre><code>order_type = 'a' class Population (object): def __init__(self,a): self.a = a def method1 (self): self.a = self.a*2 return self def method2 (self): self.a += 2 return self def method3 (self): self.a = 0 return self if order_type=='a': order = [Population.method1, Population.method2, Population.method3] elif order_type=='b': order = [Population.method2, Population.method1, Population.method3] else : order = [Population.method3, Population.method2, Population.method1] my_pop = Population(3) while iteration &lt; 100: iteration +=1 for method_to_use in order: method_to_use(my_pop) </code></pre> <p>If you want to pass more than one argument, simply use the <code>*args</code> syntax:</p> <pre><code>if order_type=='a': order = [Population.method1, Population.method2, Population.method3] arguments = [(), (), (the_argument,)] elif order_type=='b': order = [Population.method2, Population.method1, Population.method3] arguments = [(), (), (the_argument,)] else : order = [Population.method3, Population.method2, Population.method1] arguments = [(the_argument, ), (), ()] my_pop = Population(3) while iteration &lt; 100: iteration +=1 for method_to_use, args in zip(order, arguments): method_to_use(my_pop, *args) </code></pre> <p>The <code>()</code> is an empty tuple, hence <code>*args</code> will expand to no additional arguments, while <code>(the_argument,)</code> is a 1-element tuple that will pass the argument to the method.</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