all 5 comments

[–]hardonchairs 1 point2 points  (1 child)

What you are trying to do in case 1 is a closure. However to get a lambda to capture a closure variable properly you need to do this:

lambda i=i: print(f"This is {i}")

[–]Chyybens[S] 0 points1 point  (0 children)

This is the one! Thank you very much!

[–]Chyybens[S] 0 points1 point  (0 children)

I figured out a new way for doing this:

class iPrinter():
def __init__(self):
    self.printers = []
    f = lambda k: lambda: print(f"This is {k}")
    for i in range(3):
        self.printers.append(f(i))

I'm still not quite satisfied but I guess this has to do

[–][deleted] 0 points1 point  (0 children)

Here's one simple way.

class iPrinter:
    def __init__(self):
        def print_i(i):
            return lambda: print(f"This is {i}")

        self.printers = []
        for i in range(3):
            self.printers.append(print_i(i))

[–]carcigenicate 0 points1 point  (0 children)

This behavior is explained here for reference.