title: Using setattr to freeze some parameters of a method
body: <p>in order to automatically generate parameterized tests, I am trying to add methods to a class in by freezing some parameters of an existing method. Here is the piece of Python 3 code</p>
  
  <pre><code>class A:
      def f(self, n):
          print(n)
  
  params = range(10)
  
  for i in params:
      name = 'f{0}'.format(i)
      method = lambda self: A.f(self, i)
      setattr(A, name, method)
  </code></pre>
  
  <p>However, the following lines then produce rather disappointing output</p>
  
  <pre><code>a = A()
  a.f0()
  </code></pre>
  
  <p>prints "9" (instead of "0"). I must be doing something wrong, but I can't see what. Can you help ?</p>
  
  <p>Thanks a lot </p>
  
  <hr>
  
  <p>Edit: this question is indeed a duplicate. I would like to acknowledge the quality of all comments, which go much deeper than the raw answer.</p>