Dynamic methods and lambda functions

coutinhotiago at gmail.com coutinhotiago at gmail.com
Thu Jan 29 17:21:39 CET 2009


On Jan 28, 11:32 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Wed, 28 Jan 2009 16:05:39 -0200, coutinhoti... at gmail.com  
> <coutinhoti... at gmail.com> escribió:
>
> >   I had the same problem myself.
> >   Mark's detailed explanation really helped me understand.
>
> >   I ended up doing something like:
>
> The code doesn't work as-is, could you please post a working version? Just  
> for the record, so people reading this thread later don't get confused.
>
> --
> Gabriel Genellina

Sure! This works for me:

class A:
  def __init__(self):
    names = 'n1', 'n2'
    for n in names:
      setattr(self, "get%s" % n, self._createGetter(n))

  def _createGetter(self, n):
    def f(): return n
    return f

if __name__ == "__main__":
    a=A()
    print a.getn1()
    print a.getn2()



More information about the Python-list mailing list